![](/img/trans.png)
[英]Entity Framework Non-nullable column is mapped to a nullable entity property
[英]Entity Framework Code first making a column non-nullable
我首先在我的項目中使用 EF 代碼。 我的數據模型中有以下代碼
[HiddenInput(DisplayValue = false)]
public DateTime? PasswordDate { get; set; }
為了使這個不可為空,我刪除了 '?' 並從包管理器控制台運行 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());
}
}
但是當我運行 Update-Database 命令時:
Update-Database -SourceMigration 201309020721215_PasswordDate
我收到以下錯誤:無法將值 NULL 插入列 'PasswordDate', table ''; 列不允許空值。 更新失敗。 該語句已終止。
請提出解決方案。
那是因為您在該列中允許NULL
值,然后嘗試使其不可為空。 隨后它會嘗試將您現有的數據遷移到那個新的不可為空的列中,這會中斷,因為您已經在那里有了NULL
值。
兩種解決方案:
1)將其改回可空
2)為沒有值的項目賦予默認值。
如果沒有為該列提供默認值,則無法直接將不可為空的列添加到表中有歷史數據的表中。
我做的是
代碼示例(使用 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));
}
EF 核心 6 中的另一種方法是更改遷移腳本,其中添加列指定了默認值。 然后您可以稍后再次刪除此默認值。
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");
}
}
在這里發布這個是因為這是我在谷歌搜索時遇到的第一個條目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.