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

Set decimal precision for query result object

我有一个通过 Nuget 提供给我的 class。我没有来源。

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

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

所以在我的 DbContext 中我有

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

我使用

填充列表
var specialProducts =   connect.SpecialProducts.FromSql("spGetSpecialProducts").ToList()

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

的消息

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()’.

我看了this question想试试

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

但是没有属性.HasPrecision

我应该尝试什么?

[更新]

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

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

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

唯一的方法是使用 HasColumnType 并指定数据库特定类型。如果您需要支持不同的数据库,则必须使用 if 语句和针对每种数据库类型使用不同的 HasColumnType

对于 SqlServer,它将是

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

source

从 EF Core 2.0 开始,就有了 IEntityTypeConfiguration。如果您正在使用该方法,您可以按如下方式解决它:

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());

有关使用模型构建器的更多信息,请参阅Microsoft Docs