code first 数据迁移:新增字段出现 不能将值 NULL 插入列 'ProductAttribute',表 'dbo.StoreProduct';列不允许有空值。UPDATE 失败。

使用code first 做数据迁移新增非空字段,提示如下错误: 

AlterColumn("dbo.StoreProduct", "StoreProductAttribute", c => c.String(nullable: false, maxLength: 20, defaultValue: "固定资产"));

不能将值 NULL 插入列 'ProductAttribute',表 'dbo.StoreProduct';列不允许有空值。UPDATE 失败。

语句已终止。

由于数据表StoreProduct中ProductAttribute值有部分为NULL,做迁移就会出现这样的错误。

解决办法是在修改字段属性前,先赋值 给 ProductAttribute 字段。

public override void Up()
        {
            Sql("update StoreProduct set StoreProductAttribute='固定资产'");

            AlterColumn("dbo.StoreProduct", "StoreProductAttribute", c => c.String(nullable: false, maxLength: 20, defaultValue: "固定资产"));
        }
原文地址:https://www.cnblogs.com/chear/p/2890020.html