简体   繁体   English

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

[英]Entity Framework Code first making a column non-nullable

I am using EF code first for my project.我首先在我的项目中使用 EF 代码。 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.并从包管理器控制台运行 Add-Migration 命令。 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());
    }
}

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 '';我收到以下错误:无法将值 NULL 插入列 'PasswordDate', table ''; column does not allow nulls.列不允许空值。 UPDATE fails.更新失败。 The statement has been terminated.该语句已终止。

Kindly suggest the solutions.请提出解决方案。

That's because you allowed NULL values in that column, then tried to make it non-nullable.那是因为您在该列中允许NULL值,然后尝试使其不可为空。 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.随后它会尝试将您现有的数据迁移到那个新的不可为空的列中,这会中断,因为您已经在那里有了NULL值。

Two solutions:两种解决方案:

1) Change it back to nullable 1)将其改回可空
2) Give it a default value for items that don't have a value. 2)为没有值的项目赋予默认值。

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.提供一个 sql 脚本来填充这个新添加的列。
  3. alter the column to make is as non-nullable.更改要制作的列不可为空。

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

Another way in EF core 6 would be to alter the migration script where the add column specifies a default value. EF 核心 6 中的另一种方法是更改​​迁移脚本,其中添加列指定了默认值。 You can then later drop this default value again.然后您可以稍后再次删除此默认值。

public partial class AddOrderSource : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        // Add the column with a default value, then drop the default value.
        // This creates a non-nullable column without the migration failing because of existing data.

        migrationBuilder.AddColumn<int>(
            name: "OrderSource",
            table: "Orders",
            type: "int",
            nullable: false,
            defaultValue: 1); // Sample default value

        migrationBuilder.AlterColumn<int>(
            name: "OrderSource", 
            table: "Orders",
            oldDefaultValue: 1,
            defaultValue: null
        );
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "OrderSource",
            table: "Orders");
    }
}

Posting this here because this is one of the first entries i hit whilst googling.在这里发布这个是因为这是我在谷歌搜索时遇到的第一个条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架不可为空的列映射到可为空的实体属性 - Entity Framework Non-nullable column is mapped to a nullable entity property 实体框架5 DbUpdateException:非可空成员的空值 - Entity Framework 5 DbUpdateException: Null value for non-nullable member 用于关系的代码优先虚拟属性仍然使用不可为空的列构建 - Code first virtual property for relationship still builds with a non-nullable column 使非可空值类型可为空 - Making a Non-nullable value type nullable 非空POCO属性的EF代码优先 - EF Code First Exception on non-nullable POCO property 删除具有非空外键关系实体框架的实体5 POCO - Delete entity with non-nullable foreign key relationship entity framework 5 POCO 我可以使用实体框架中的更新方法更新实体中的不可为空值吗? - Can i update a non-nullable value in an Entity by using Update method from Entity Framework? 将可为空的字段装饰为代码优先Linq to SQL的不可为空属性 - Decorating a nullable field as a non-nullable property for code first Linq to SQL 禁止 DatabaseGenerated 列上的不可为空属性 - Suppress Non-nullable property on DatabaseGenerated column 我在实体框架中获得了非空外键的空值 - I get a null value for a non-nullable foreign key with the entity framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM