C# 实体框架代码首先使列不可为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18569003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:37:14  来源:igfitidea点击:

Entity Framework Code first making a column non-nullable

c#sqlentity-framework

提问by HBhatia

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

我首先在我的项目中使用 EF 代码。我的数据模型中有以下代码

[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.

为了使这个不可为空,我删除了 '?' 并从包管理器控制台运行 Add-Migration 命令。生成了以下迁移文件。

  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());
    }
}

But when I run Update-Database command:

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

Update-Database -SourceMigration 201309020721215_PasswordDate

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 插入列 'PasswordDate', table ''; 列不允许空值。更新失败。该语句已终止。

Kindly suggest the solutions.

请提出解决方案。

采纳答案by mattytommo

That's because you allowed NULLvalues 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 NULLvalues in there.

那是因为您允许NULL该列中的值,然后尝试使其不可为空。随后它会尝试将您现有的数据迁移到新的不可为空的列中,这会中断,因为您已经NULL在那里有了值。

Two solutions:

两种解决方案:

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

1) 将其改回可为空
2) 为没有值的项目赋予默认值。

回答by Ike

It's not possible to directly add a non-nullable column to a table that has historical data in the table if no default value is provided for that column.

如果没有为该列提供默认值,则无法直接将不可为空的列添加到表中有历史数据的表中。

What I do is

我做的是

  1. add the column as nullable.
  2. provide an sql script to populate this newly added column.
  3. alter the column to make is as non-nullable.
  1. 将该列添加为可为空。
  2. 提供一个 sql 脚本来填充这个新添加的列。
  3. 更改要制作的列不可为空。

Code example(with postgres database):

代码示例(使用 postgres 数据库):

 public override void Up()
    {            
        AddColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: true));
        Sql(@"UPDATE ""public"".""YourTableName""
              SET ""YourColumnName"" = Value you want to set
            ");

        AlterColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: false));
    }