我正在使用 EF Core 8 开发 .NET 7 项目,并尝试将代码优先迁移与 Microsoft SQL Server 结合使用,但由于某种原因,我无法在迁移中生成任何默认值。
型号:
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
给定上述类时,生成的迁移不包含任何 defaultValue 规范:
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")
有人可以帮我找出我做错了什么吗?
事实证明我的 Fluent 配置根本没有被应用。需要添加以下代码到
TdeContext
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new TestConfiguration());
}
现在迁移正如预期的那样。
(你知道事情是怎么回事。你在墙上撞了一天,最后向 SO 提出了一个问题,五分钟后才弄清楚。)