使用 entity framework 保存到 Db 时设置精度和比例

Set precision and scale while saving into Db using entity framework

这就是 JSON 响应:

{
  "data": [
    {
      "someTicketNum": "123456",
      "someTemperature": 2,
      "somePercent": 2.025
    }
  ]
}

需要保存到的table建模为:

public class TableName
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long TicketID { get; set; }
    public float? SomeTemperature { get; set; }
    public decimal? SomePercent { get; set; }
}

这些 Db 列设置为:SomeTemperature(decimal(3,1), null)SomePercent(decimal(7,5), null)

我希望按如下方式保存这些属性的值:

SomeTicketNum: "123456",
SomeTemperature: 2.0,  // The examples values are: 0.0, 1.5, 99.9 etc.
SomePercent: 2.02500 // The example values are: 0.00000, 1.50000, 99.99999 etc.

我已经在模型构建器中试过了:

modelBuilder.Entity<TableName>().Property(x => x.SomeTemperature).HasPrecision(3,1);
modelBuilder.Entity<TableName>().Property(x => x.SomePercent).HasPrecision(7, 5);

原来 .HasPrecision 只能在 decimal 属性中设置,所以我将 SomeTemperature 的数据类型更改为 decimal?,这使得错误消失了,原来是说:

'PrimitivePropertyConfiguration' does not contain a definition for 'HasPrecision' and no accessible extension method 'HasPrecision' accepting a first argument of type 'PrimitivePropertyConfiguration' could be found (are you missing a using directive or an assembly reference?)

我在尝试将此记录保存到 Db 时无法弄清楚这个 exception,它说:

Inner Ex. Msg: String or binary data would be truncated. The statement has been terminated.

我已经对齐了 db 和 c# 模型中的所有数据类型。

我在这里做错了什么? P.S。我正在使用 EF6。

您使用 HasPrecision 的方法应该有效:

modelBuilder.Entity<TableName>().Property(x => x.SomeTemperature).HasPrecision(3,1);
modelBuilder.Entity<TableName>().Property(x => x.SomePercent).HasPrecision(7, 5);

问题是 HasPrecision 仅针对 decimal(和 DateTime 但此处不相关)属性定义,因此您需要更改 SomeTemperature 属性 输入 decimal?.

关于异常:

Inner Ex. Msg: String or binary data would be truncated. The statement has been terminated.

我试图用这样的硬编码值保存其他字段:

SomeOtherField = (decimal)0.00000

浮点数不能保存到小数域(SomeOtherField是小数),所以改成:

SomeOtherField = 0.00000m

成功了!