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无法识别你定义的默认值规则。
解决步骤:
- 在
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); } }
- 删除已生成的无效迁移,重新生成:
Remove-Migration Add-Migration TestMigration
额外排查点:
- 确认配置类的命名空间已被上下文所在类正确引用
- 如果项目存在多个DbContext,执行迁移时需通过
-Context参数指定目标上下文:Add-Migration TestMigration -Context TdeContext
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

