【发布时间】:2018-04-20 01:30:23
【问题描述】:
我正在开发一个新的代码优先实体框架(使用 dbMigration)解决方案,但我遇到了一些我无法克服的障碍。
即使我修改了生成的迁移文件以将十进制字段的精度/小数位数设置为 18 和 9,但当我运行 update-database 来构建数据库并调用我编写的为数据播种的方法时,它是四舍五入的数据保留到小数点后 2 位,而不是我预期的 9 位。在我尝试播种的示例数据中,我尝试将 Price 属性设置为 0.4277,但它在数据库中显示为 0.420000000
我一直在寻找解决这个问题的方法,包括为 OnModelCreating 创建一个覆盖(在我的上下文类中),以强制那里的精度/比例。但是当我把它准备好时(参见下面代码中注释掉的行),虽然数据库迁移仍然完全按计划工作(包括按预期创建 DECIMAL(18,9)),但现在 Seed 调用不运行.
我希望我只是遗漏了一些小东西(而且很容易修复)。但是谁能提供我可以尝试的建议?
以下是相关代码(包括最初生成的迁移代码):
public class Product
{
public int ID { get; set; }
public decimal Price { get; set; }
}
internal sealed class Configuration : DbMigrationsConfiguration<ConfiguratorContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(ConfiguratorContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
SeedData.Initialize();
}
}
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Products",
c => new
{
ID = c.Int(nullable: false, identity: true),
Price = c.Decimal(nullable: false, precision: 18, scale: 9)
})
.PrimaryKey(t => t.ID);
}
public override void Down()
{
DropTable("dbo.Products");
}
}
public class ConfiguratorContext : DbContext
{
public ConfiguratorContext() : base("name=ConfiguratorConnectionString")
{
Database.SetInitializer<ConfiguratorContext>(new CreateDatabaseIfNotExists<ConfiguratorContext>());
}
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Entity<Product>().Property(a => a.Price).HasPrecision(18, 9);
}
}
public class SeedData
{
public static void Initialize()
{
using (var context = new ConfiguratorContext())
{
if (context.Products.Any())
{
return; // DB has been seeded
}
context.Products.Add(new Product
{
Price = Convert.ToDecimal(0.4277),
});
context.SaveChanges();
}
}
}
我错过了什么?
谢谢!
【问题讨论】:
-
你的种子是
CreateDatabaseIfNotExists。它应该只运行一次,直到您真正删除数据库。 -
是的,出于测试目的,我一直在手动删除数据库(目前)来测试它,当我这样做时,它仍然会将 (18,9) 小数点截断为小数点后 2 位。
标签: c# entity-framework-6 dbmigrator