如何解决设置精度和比例,同时使用实体框架保存到Db中
这是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?
,这使错误消失了,原本是这样说的: / p>
'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?)
试图将记录保存到exception
时,我只是无法弄清楚这个Db
,它说:
Inner Ex. Msg: String or binary data would be truncated. The statement has been terminated.
我已经将db和c#模型中的所有数据类型对齐了。
我在这里做错了什么? 附言我正在使用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
成功了!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。