代码优先循环参考外键配置

时间:2012-08-21 11:24:55

标签: entity-framework ef-code-first

以下代码在未注释所有代码时创建外键错误。

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int FavoriteChildId { get; set; }
    public Child FavoriteChild { get; set; }
    //public int WorstChildId { get; set; }
    public Child WorstChild { get; set; }
    public ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    //public int ParentId { get; set; }
    public Parent Parent { get; set; }
}

public class CFContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }
}

如果未指定外键名称但是无法编辑模型,则此方法有效。有谁知道如何指定外键名称?

1 个答案:

答案 0 :(得分:3)

遵循命名约定将在上面创建正确的FK - 您的代码:

public int WorstChildId { get; set; }
public Child WorstChild { get; set; }

是否为WorstChild创建WorstChildId的FK。但是,当我尝试上面的代码时,我得到了多个删除路径错误(父 - &gt; WorstChild - &gt; ChildTable,父 - &gt; FavoriteChild - &gt; ChildTable)

您可以将其中一个或两个映射设置为不在删除时级联,这样可以解决您的问题:

public class CFContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithRequiredPrincipal(p => p.WorstChild)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Child>()
         .HasRequired(c => c.Parent)
         .WithRequiredPrincipal(p => p.FavoriteChild)
         .WillCascadeOnDelete(false);
    }
}