No Type Specified for the Decimal Column

转:https://www.colabug.com/3536556.html 

If you are using Entity Framework in a .NET Core project, you might run into the following issue if you have decimal fields.

Microsoft.EntityFrameworkCore.Model.Validation[30000]
No type was specified for the decimal column 'Price' on entity type 'Product'. 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 means Entity Framework will provide a default precision to the database. The default is (18, 2). That means it will store 18 total digits, with 2 of those digits being to the right of the decimal point.

If your record has more than 2 decimal points, SQL Server will truncate the extras.
If your record has more than 18 total digits, you will get an "out of range" error.
The easiest fix is to use Data Annotations to declare a default on your model. The data annotation looks like: [Column(TypeName = "decimal(18,2)")]

For a model named Product with a Price attribute, it would look like this:

public class Product {
    public int ID { get; set; }
    public string Title { get; set; }
    [Column(TypeName = "decimal(18,2)")]
    public decimal Price { get; set; }
}
You can adjust the value away from the default 18, 2 if you need.

You can also add it to the OnModelCreating method of your DbContext implementation instead of the above method. That would look like this:

modelBuilder.Entity()
    .Property(p => p.Price)
    .HasPrecision(18, 2);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值