Set decimal precision for query result object

c# entity-framework-core entity-framework-core-2.1


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?


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
9/14/2019 11:51:54 PM

Accepted 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

    .Property(o => o.GoldPercent)
9/14/2019 9:25:03 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow