EF代码首先使用空查找表设置外键

时间:2014-03-05 11:47:43

标签: c# asp.net-mvc entity-framework ef-code-first ef-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; }
}

TestType是一个典型的查找表,我通常用Seed()方法填充它们:

context.TestTypes.AddOrUpdate(
    it => it.Name,
    new TestType() { Name = "Drug" },
    new TestType() { Name = "Educational" },
    new TestType() { Name = "Other" }
);

当我创建具有关系的表时,我得到以下迁移:

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);

现在,如果我执行迁移,我会收到一个错误,因为查找表仍然为空并且创建的列没有默认值,因此无法遵守外键。

开发中,我可以通过简单地创建两个迁移来解决这个问题,第一个是创建查找表,第二个是设置外键。如果我单独运行它们,那么第一个之后的Seed方法将填充表格,我可以调整列创建以从DB中获取值以在创建外键之前预填充列,有点像这样:

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);

然后,当我运行它时,一切正常。

现在,在 PRODUCTION 中,我没有同样的奢侈品,因为所有迁移都是在Seed方法运行之前运行的,我将始终遇到同样的问题。

我知道我可以潜在地在生产数据库上按步骤顺序运行迁移但是这并没有真正解决问题...让我们说我的同事更新他的工作副本并运行迁移,所有都将按顺序运行,他肯定会遇到错误。

1 个答案:

答案 0 :(得分:0)

我不确定数据库的当前状态,但我会像这样定义你的模型

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; }
}

当表不存在时,会导致以下迁移。我总是发现描述外键明确地工作得更好。

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);
}

只要Test表为空,种子就可以正常工作了吗?