我有一个使用 EF 和代码优先的 MVC 项目。
我有一个模型 PropBase 和一个模型 MyProp - 它们被映射到同一个表(带有自动“鉴别器”列)。
我向 MyProp 添加了两个属性 - prop1 和 prop2:
public class PropBase
{
public double Prop0 { get; set; }
}
public class MyProp: PropBase
{
public double Prop10 { get; set; }
public double Prop1{ get; set; } // new property
public int Prop2{ get; set; } // new property
}
而且我还添加了一个新的迁移:
public partial class AddProps12 : DbMigration
{
public override void Up()
{
AddColumn("dbo.Props", "Prop1", c => c.Double(nullable: true, defaultValue: 0));
AddColumn("dbo.Props", "Prop2", c => c.Int(nullable: true, defaultValue: 0));
}
public override void Down()
{
DropColumn("dbo.Props", "Prop1");
DropColumn("dbo.Props", "Prop2");
}
}
但是当我运行应用程序时 - 新列添加了 null 并在线上
return m_myPropsRepository.AsQueryable().ToList();
我收到这个错误
The 'Prop1' property on 'MyProp' could not be set to a 'null' value. You must set this property to a non-null value of type 'Double'.
我不能使用 nullable:false,因为当我向表中插入一个新的 PropBase 时 - 它不知道 Prop1 和 Prop2,因此插入 NULL,然后我得到一个错误,因为我将它定义为不可为空。
我需要一种方法让它可以为 nullAND 以将 0 作为当前 MyProp 行的默认值。
最佳答案
请试试
AddColumn("dbo.Props", "Prop1", c => c.Double());
AddColumn("dbo.Props", "Prop2", c => c.Int());
Sql("UPDATE dbo.Props SET Prop1 = 0, Prop2 = 0 WHERE Discriminator = 'MyProp'");
这个想法是用非空值更新数据库表中带有鉴别器“MyProp”的旧值
关于c# - 迁移中的默认值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27793922/