修复数据库迁移Microsoft.EntityFrameworkCore.Model.Validation[30000]

参考文章:https://mattferderer.com/entity-framework-no-type-was-specified-for-the-decimal-column


此问题一般发生在Entity Framework Core 项目迁移时,包含decimal类型字段。

报错信息为:

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()'.


这意味着EF将提供默认的精度给数据库,默认值一般是(18,2),意思是存储18位数字和2位小数。

如果小数位超过2位,就会截断。

如果数字位超过18位,就会报错"out of range"。


解决方案:

一、给模型的属性进行注解,约定精度;

注解格式:[Column(TypeName = "decimal(18,2)")]

例:

public class Product {
   public int ID { get; set; }
   public string Title { get; set; }
   [Column(TypeName = "decimal(18,2)")]
   public decimal Price { get; set; }
}

二、添加到项目DbContext的OnModelCreating方法:

例:

protected override void OnModelCreating(ModelBuilder modelBuilder){
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Product>()
        .Property(p => p.Price)
        .HasColumnType("decimal(18,2)");
}



上一篇:无

下一篇:Service调用方式