You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁用EF Core 6 Code First迁移的默认值生成行为

EF Core 6 Code First 生成必填字段时自动添加空默认约束的问题

我在使用EF Core 6的Code First模式开发时遇到一个问题:当定义带有必填字段的新实体时,EF生成的迁移脚本总会给该字段添加空默认约束,示例如下:

migrationBuilder.AlterColumn<Guid>(
    name: "TenantId",
    table: "Sites",
    type: "uniqueidentifier",
    nullable: false,
    defaultValue: new Guid("00000000-0000-0000-0000-000000000000"),  // 多余的默认约束
    oldClrType: typeof(Guid),
    oldType: "uniqueidentifier",
    oldNullable: true);

大多数场景下我不需要任何默认值,尝试过通过模型配置禁用这个行为,但没有效果:

builder.Property(cc => cc.TenantId).HasDefaultValue(null);
builder.Property(cc => cc.TenantId).HasDefaultValueSql(null);

我使用以下命令生成迁移:

dotnet ef migrations add --context:DataContext --project "xxx" xxxx

我没找到针对这个特定问题的相关解答,类似问题的答案都是让手动修改生成的迁移脚本。我有以下疑问:

  • 手动修改迁移脚本会不会导致代码与数据库架构不一致?
  • 如果必须手动修改,这么做的合理性是什么?为什么不需要担忧?

附加细节(未启用可空类型)

public class Site
{
    public Tenant Tenant { get; set; }

    public Guid TenantId { get; set; }

    public Guid Id { get; set; }

    // 其他属性...
}

public class Tenant
{
    public Guid Id { get; set; }

    // 其他属性...
}

public class SiteEntityTypeConfiguration : IEntityTypeConfiguration<Site>
{
    public void Configure(EntityTypeBuilder<Site> builder)
    {
        builder.HasOne(cc => cc.Tenant)
            .WithMany()
            .OnDelete(DeleteBehavior.Restrict);
    }
}

内容的提问来源于stack exchange,提问作者Lukas K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:05:26