Tal*_*ris 5 c# asp.net-mvc entity-framework ef-code-first entity-framework-migrations
我遇到与查找表和外键相关的 EF 代码优先迁移问题。假设我的代码中有这两个类:
public class Test
{
[Key]
public long Id { get; set; }
[Required]
public string Title { get; set; }
[Required, DisplayName("Test type")]
public TestType TestType { get; set; }
}
public class TestType
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
TestType
是一个典型的查找表,我通常在方法中填充它们Seed()
:
context.TestTypes.AddOrUpdate(
it => it.Name,
new TestType() { Name = "Drug" },
new TestType() { Name = "Educational" },
new TestType() { Name = "Other" }
);
Run Code Online (Sandbox Code Playgroud)
当我创建具有关系的表时,我得到以下迁移:
CreateTable(
"dbo.TestTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
AddColumn("dbo.Tests", "TestType_Id", c => c.Int(nullable: false));
CreateIndex("dbo.Tests", "TestType_Id");
AddForeignKey("dbo.Tests", "TestType_Id", "dbo.TestTypes", "Id", cascadeDelete: true);
Run Code Online (Sandbox Code Playgroud)
现在,如果我执行迁移,我当然会收到错误,因为考虑到查找表仍然为空并且创建的列没有默认值,因此无法遵守外键。
在开发中,我可以通过简单地创建两个迁移来解决这个问题,第一个迁移用于创建查找表,第二个迁移用于设置外键。如果我单独运行它们,那么第一个方法之后的 Seed 方法将填充表,并且我可以调整列创建以从数据库中获取值以在创建外键之前预填充列,有点像这样:
AddColumn("dbo.Tests", "TestType_Id", c => c.Int(nullable: false));
Sql("UPDATE dbo.Tests SET TestType_Id = (SELECT TOP 1 Id FROM dbo.TestTypes)");
CreateIndex("dbo.Tests", "TestType_Id");
AddForeignKey("dbo.Tests", "TestType_Id", "dbo.TestTypes", "Id", cascadeDelete: true);
Run Code Online (Sandbox Code Playgroud)
然后当我运行它时一切正常。
现在,在生产中我没有同样的奢侈,因为所有迁移都是在运行种子方法之前运行的,所以我总是会遇到同样的问题。
我知道我也可能在生产数据库上按逐步顺序运行迁移,但这并不能真正解决问题...假设我的一位同事更新了他的工作副本并运行迁移,所有操作都将按顺序运行并且他肯定会遇到这个错误。
我不确定你的数据库的当前状态,但我会像这样定义你的模型
public class Test
{
[Key]
public long Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
[ForeignKey("TestType")]
public int TestTypeId { get; set; }
[DisplayName("Test type")]
public virtual TestType TestType { get; set; }
}
public class TestType
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当表尚不存在时,这会导致以下迁移。我总是发现明确描述外键效果更好。
public override void Up()
{
CreateTable(
"dbo.Tests",
c => new
{
Id = c.Long(nullable: false, identity: true),
Title = c.String(nullable: false),
TestTypeId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.TestTypes", t => t.TestTypeId)
.Index(t => t.TestTypeId);
CreateTable(
"dbo.TestTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
}
Run Code Online (Sandbox Code Playgroud)
只要测试表为空,种子就应该可以正常工作吗?
归档时间: |
|
查看次数: |
1283 次 |
最近记录: |