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

Entity framework 代码优先循环参考外键配置,entity-framework,ef-code-first,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; } p

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

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; }
}
公共类父类
{
公共int Id{get;set;}
公共字符串名称{get;set;}
public int-FavoriteChildId{get;set;}
公共子项FavoriteChild{get;set;}
//public int WorstChildId{get;set;}
公共子WorstChild{get;set;}
公共ICollection子项{get;set;}
}
公营儿童
{
公共int Id{get;set;}
公共字符串名称{get;set;}
//public int ParentId{get;set;}
公共父级{get;set;}
}
公共类CFContext:DbContext
{
公共数据库集父项{get;set;}
公共DbSet子项{get;set;}
}

如果未指定外键名称,但无法编辑模型,则可以使用它。有人知道如何指定外键名称吗?

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

public int WorstChildId { get; set; }
public Child WorstChild { get; set; }
为WorstChild创建WorstChildId的FK。然而,当我尝试上面的代码时,我得到了一个多删除路径错误(Parent->WorstChild->ChildTable,Parent->FavoriteChild->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);
    }
}
公共类CFContext:DbContext
{
公共数据库集父项{get;set;}
公共DbSet子项{get;set;}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasRequired(c=>c.Parent)
.WithRequiredPrincipal(p=>p.WorstChild)
.WillCascadeOnDelete(假);
modelBuilder.Entity()
.HasRequired(c=>c.Parent)
.WithRequiredPrincipal(p=>p.FavoriteChild)
.WillCascadeOnDelete(假);
}
}

谢谢@Mark,您的解决方案对上述示例非常有效。不幸的是,我需要一个第三个亲子参考,这似乎不起作用。如果您有时间,请查看我的最新问题,其中包含问题代码。