Search code examples
c#entity-framework-coreentity-framework-core-2.1

Set decimal precision for query result object


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

Solution

  • Update: EF Core 5 and later provides HasPrecision with both precision and scale arguments, which is now the preferred way for this task, e.g.

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

    Original: 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)");