Set decimal precision for query result object

19.7k Views Asked by At

I have a class supplied to me via Nuget. I don't have the source.

 public class SpecialProductResult
  {
    public int id { get; set; }
    public decimal SpecialPercent {get;set;}
  }

I want to populate a list of SpecialProductResult from a stored procedure

So in my DbContext I have

public DbQuery<SpecialProductDto> SpecialProducts { get; set; }

I populate the list using

var specialProducts =   connect.SpecialProducts.FromSql("spGetSpecialProducts").ToList()

In the error log I see messages like

No type was specified for the decimal column ‘“SpecialPercent”’ on entity type ‘“SpecialProductResult”’. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using ‘ForHasColumnType()’.

I looked at this question and wanted to try

modelBuilder.Entity<SpecialProductResult>().Property(o => o.GoldPercent).HasPrecision(18,4)

But there is no property .HasPrecision

What should I try?

[Update]

I tried Ivan Stoev's answer but received a runtime error

The entity type 'SpecialProductResult' cannot be added to the model because a query type with the same name already exists
3

There are 3 best solutions below

6
Ivan Stoev On BEST ANSWER

Currently EF Core does not provide database independent way of specifying the numeric type precision and scale (similar to EF6 HasPrecision).

The only way to do that is to use HasColumnType and specify the database specific type. If you need to support different databases, you have to use if statements and different HasColumnType for each database type.

For SqlServer, it would be

modelBuilder.Query<SpecialProductResult>()
    .Property(o => o.GoldPercent)
    .HasColumnType("decimal(18,4)");
0
Ahmad Hamdy Hamdeen On
public class Part
{
    public Guid PartId { get; set; }
    public string Number { get; set; }
    [Column(TypeName = "decimal(18,4)")] // <--
    public decimal Size { get; set; }
}

source

0
Chris Franco On

Since EF Core 2.0 there is IEntityTypeConfiguration. In case you are using that approach, you can solve it as follows:

class PartConfiguration : IEntityTypeConfiguration<Part>
{
  public void Configure(EntityTypeBuilder<Part> builder){
    
     builder.Property(c => c.PartId);
     builder.Property(c => c.Number);
     builder.Property(c => c.Size)
            .HasPrecision(18, 4) <-- Use Either This
            .HasColumnType("decimal(18,4)"); <-- Or this
  }
}

...
// OnModelCreating
builder.ApplyConfiguration(new PartConfiguration());

For more information about using the ModelBuilder please refer to Microsoft Docs