【问题标题】:Set precision and scale while saving into Db using entity framework在使用实体框架保存到 Db 时设置精度和比例
【发布时间】:2020-09-22 14:24:32
【问题描述】:

这是 JSON 响应的内容:

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

需要保存的表建模为:

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# 模型中的所有数据类型。

我在这里做错了什么? 附言我正在使用 EF6。

【问题讨论】:

  • 你似乎在这里混合了很多东西。 JSON 格式 -> 不相关。 C# 格式 -> 不相关。 DB 格式 -> 相关。 Entity Framework 将根据您拥有的 C# 值使用正确的 DB 格式。而没有,仅仅因为你看到SomeTemperature2.00就意味着该值为2.00
  • 你能描述一下实际的问题吗?
  • 嗨@GuruStron,我现在为这个问题添加了更多细节。
  • 尝试使用.HasColumnType("decimal(3,1)").HasColumnType("decimal(7,5)")来代替HasPrecision
  • @AshK 将作为答案添加)

标签: c# .net entity-framework decimal


【解决方案1】:

您使用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?

【讨论】:

    【解决方案2】:

    关于异常:

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

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

    SomeOtherField = (decimal)0.00000
    

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

    SomeOtherField = 0.00000m
    

    成功了!

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 2012-02-29
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多