c# - 迁移中的默认值不起作用

标签 c# entity-framework-5 entity-framework-migrations

我有一个使用 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/

相关文章:

c# - INSERT 语句与 FOREIGN KEY 约束错误冲突

postgresql - PostgreSQL 中从字符串到 uuid 的迁移

c# - Entity Framework 6 错误无法加载指定的元数据资源

c# - 如何将 Expression<Func<T, bool>> 转换为 Predicate<T>

c# - Ninject - 如何在范围内保存常量?

c# - ASP.MVC 参数未传递给 http post 的 Action 方法

c# - Entity Framework 5 Fluent API - 配置单向关系

asp.net-mvc - 使用 EF 6 和 MVC 5 中的代码优先方法将新表添加到现有数据库

c# - Entity Framework 代码优先级联删除一对多

c# - 我怎么知道 automapper 是否已经初始化?