设置查询结果对象的小数精度

Kir*_*eed 5 c# entity-framework-core entity-framework-core-2.1

我有一个通过 Nuget 提供给我的课程。我没有消息来源。

 public class SpecialProductResult
  {
    public int id { get; set; }
    public decimal SpecialPercent {get;set;}
  }
Run Code Online (Sandbox Code Playgroud)

我想从存储过程中填充 SpecialProductResult 列表

所以在我的 DbContext 我有

public DbQuery<SpecialProductDto> SpecialProducts { get; set; }
Run Code Online (Sandbox Code Playgroud)

我使用填充列表

var specialProducts =   connect.SpecialProducts.FromSql("spGetSpecialProducts").ToList()
Run Code Online (Sandbox Code Playgroud)

在错误日志中,我看到类似的消息

未为实体类型“SpecialProductResult”上的十进制列“SpecialPercent”指定类型。如果它们不符合默认精度和小数位数,这将导致值被静默截断。使用“ForHasColumnType()”显式指定可以容纳所有值的 SQL 服务器列类型。

我看着这个问题,想试试

modelBuilder.Entity<SpecialProductResult>().Property(o => o.GoldPercent).HasPrecision(18,4)
Run Code Online (Sandbox Code Playgroud)

但是没有属性 .HasPrecision

我应该尝试什么?

[更新]

我尝试了 Ivan Stoev 的回答,但收到了运行时错误

The entity type 'SpecialProductResult' cannot be added to the model because a query type with the same name already exists
Run Code Online (Sandbox Code Playgroud)

Iva*_*oev 9

目前 EF Core 不提供指定数字类型精度和小数位数的数据库独立方式(类似于 EF6 HasPrecision)。

唯一的方法是使用HasColumnType并指定数据库特定类型。如果你需要支持不同的数据库,你必须使用if不同的语句并且HasColumnType每个数据库类型都不同。

对于 SqlServer,它将是

modelBuilder.Query<SpecialProductResult>()
    .Property(o => o.GoldPercent)
    .HasColumnType("decimal(18,4)");
Run Code Online (Sandbox Code Playgroud)


小智 9

public class Part
{
    public Guid PartId { get; set; }
    public string Number { get; set; }
    [Column(TypeName = "decimal(18,4)")] // <--
    public decimal Size { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

来源