【发布时间】: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 格式。而没有,仅仅因为你看到
SomeTemperature为2.00就意味着该值为2.00 -
你能描述一下实际的问题吗?
-
嗨@GuruStron,我现在为这个问题添加了更多细节。
-
尝试使用
.HasColumnType("decimal(3,1)")和.HasColumnType("decimal(7,5)")来代替HasPrecision。 -
@AshK 将作为答案添加)
标签: c# .net entity-framework decimal