实体框架代码首先使列不可为空 [英] Entity Framework Code first making a column non-nullable

查看:59
本文介绍了实体框架代码首先使列不可为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先在我的项目中使用EF代码.我的DataModel中有以下代码

I am using EF code first for my project. I have following code in my DataModel

[HiddenInput(DisplayValue = false)]        
public DateTime? PasswordDate { get; set; }

要使此内容不为空,我删除了'?'并从程序包管理器控制台中运行添加迁移"命令.生成了以下迁移文件.

To make this non-nullable I removed '?' and ran Add-Migration command from Package manager console. following migration file was generated.

  public partial class PasswordDate : DbMigration
{
    public override void Up()
    {
        AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime(nullable: false));
    }

    public override void Down()
    {
        AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime());
    }
}

但是当我运行Update-Database命令时:

But when I run Update-Database command:

Update-Database -SourceMigration 201309020721215_PasswordDate

我收到以下错误:无法将值NULL插入表''的"PasswordDate"列中;列不允许为空.UPDATE失败.该声明已终止.

I get following error: Cannot insert the value NULL into column 'PasswordDate', table ''; column does not allow nulls. UPDATE fails. The statement has been terminated.

请提出解决方案.

推荐答案

这是因为您在该列中允许了 NULL 值,然后试图使其变为不可为空.随后它将尝试将现有数据迁移到该新的不可为空的列,由于您已经在其中具有 NULL 值,因此该列将中断.

That's because you allowed NULL values in that column, then tried to make it non-nullable. It will subsequently try to migrate your existing data into that newly non-nullable column, which will break because you already have NULL values in there.

两种解决方案:

1)将其更改回可为空的
2)为没有值的项目提供默认值.

1) Change it back to nullable
2) Give it a default value for items that don't have a value.

这篇关于实体框架代码首先使列不可为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆