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

EF Core 8 Code First迁移未生成默认值问题求助

EF Core 8 Code First迁移未生成字段默认值问题

我正在基于.NET 7项目使用EF Core 8与Microsoft SQL Server进行Code First迁移,但迁移代码未生成字段默认值。

模型

public class Test
{
    public int TestId { get; set; }
    public string Name { get; set; }
}

配置类

public class TestConfiguration : IEntityTypeConfiguration<Test>
{
    public void Configure(EntityTypeBuilder<Test> builder)
    {
        builder.ToTable("Test", "dbo");
        builder.HasKey(x => x.TestId).HasName("PK_Test").IsClustered();

        builder.Property(x => x.TestId).ValueGeneratedOnAdd().UseIdentityColumn();
        builder.Property(x => x.Name).HasDefaultValue("TestValue");
    }
}

数据库上下文

public class TdeContext : DbContext
{
    public TdeContext(DbContextOptions options) : base(options) { }

    public DbSet<Test> Tests { get; set; }
}

执行Add-Migration TestMigration生成的迁移代码未包含默认值定义:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Tests",
        columns: table => new
        {
            TestId = table.Column<int>(type: "int", nullable: false)
                .Annotation("SqlServer:Identity", "1, 1"),
            Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Tests", x => x.TestId);
        });
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropTable(
        name: "Tests");
}

我预期的代码应为Name = table.Column<string>(type: "nvarchar(max)", nullable: false, defaultValue: "TestValue"),请问我哪里操作有误?


问题原因与解决方法

核心问题是你的配置类TestConfiguration没有被EF Core上下文加载,导致EF无法识别你定义的默认值规则。

解决步骤:

  1. 在TdeContext中重写OnModelCreating方法,手动应用配置类:
public class TdeContext : DbContext
{
    public TdeContext(DbContextOptions options) : base(options) { }

    public DbSet<Test> Tests { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 应用单个配置类
        modelBuilder.ApplyConfiguration(new TestConfiguration());
        
        // 如果项目中有多个配置类,推荐批量加载当前程序集内的所有配置
        // modelBuilder.ApplyConfigurationsFromAssembly(typeof(TestConfiguration).Assembly);
    }
}
  1. 删除已生成的无效迁移,重新生成:
Remove-Migration
Add-Migration TestMigration

额外排查点:

  • 确认配置类的命名空间已被上下文所在类正确引用
  • 如果项目存在多个DbContext,执行迁移时需通过-Context参数指定目标上下文:Add-Migration TestMigration -Context TdeContext

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 13:58:23