在实体框架6.1中使用Code First创建数据库时,十进制精度和比例不正确
本文关键字:十进制 数据库 精度 不正确 创建 First 框架 实体 Code | 更新日期: 2023-09-27 18:14:27
我有一个从我的项目中继承IdentityDbContext的模型,从ASP的项目模板创建。. NET MVC创建与Visual Studio 2013 Update 2.
public partial class MyModel : IdentityDbContext<ApplicationUser>
{
public MyModel()
: base("DefaultConnection")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyModel>());
}
//....other properties
public virtual DbSet<ProductClientDiscount> ProductClientPrice { get; set; }
public virtual DbSet<ClientCategoryDiscount> ClientCategoryDiscount { get; set; }
public virtual DbSet<Product> Products { get; set; }
//....other properties
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ClientCategoryDiscount>().Property(x => x.PercentDiscountRent).HasPrecision(12, 9);
modelBuilder.Entity<ClientCategoryDiscount>().Property(x => x.PercentDiscountSale).HasPrecision(12, 9);
modelBuilder.Entity<ProductClientDiscount>().Property(x => x.PercentDiscountRent).HasPrecision(12, 9);
modelBuilder.Entity<ProductClientDiscount>().Property(x => x.PercentDiscountSale).HasPrecision(12, 9);
modelBuilder.Entity<Product>().Property(x => x.SalePrice).HasPrecision(12, 9);
modelBuilder.Entity<Product>().Property(x => x.RentPrice).HasPrecision(12, 9);
}
}
我需要改变默认的十进制精度在数据库中,当它被创建,所以我发现在其他帖子,它应该在OnModelCreating,就像我所做的。一切似乎都很正常,但是,在创建数据库时,十进制字段获得默认的精度和十进制(18,2)的比例。我在其他帖子中看到,该模型继承自DBContext,而不是IdentityDbContext,我不知道是否有什么我需要做才能让它工作。我在Visual Studio 2013中使用localdb。感谢所有能帮助我的人。
我解决了这个问题。碰巧Visual Studio创建了一个类ApplicationDbContext作为已经继承了IdentityDbContext的项目的一部分,所以MyModel类应该继承这个类,或者我应该在ApplicationDbContext类的OnModelCreating中设置十进制属性:
public partial class MyModel : ApplicationDbContext
{
public MyModel()
: base("DefaultConnection")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyModel>());
}
//....other properties
public virtual DbSet<ProductClientDiscount> ProductClientPrice { get; set; }
public virtual DbSet<ClientCategoryDiscount> ClientCategoryDiscount { get; set; }
public virtual DbSet<Product> Products { get; set; }
//....other properties
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ClientCategoryDiscount>().Property(x => x.PercentDiscountRent).HasPrecision(12, 9);
modelBuilder.Entity<ClientCategoryDiscount>().Property(x => x.PercentDiscountSale).HasPrecision(12, 9);
modelBuilder.Entity<ProductClientDiscount>().Property(x => x.PercentDiscountRent).HasPrecision(12, 9);
modelBuilder.Entity<ProductClientDiscount>().Property(x => x.PercentDiscountSale).HasPrecision(12, 9);
modelBuilder.Entity<Product>().Property(x => x.SalePrice).HasPrecision(12, 9);
modelBuilder.Entity<Product>().Property(x => x.RentPrice).HasPrecision(12, 9);
}
}
两种方法都可以!