【问题标题】:Code First Circular Reference Foreign Key Configuration代码优先循环引用外键配置
【发布时间】:2012-08-21 21:03:41
【问题描述】:

当所有代码都没有注释时,以下代码会产生外键错误。

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

如果未指定外键名称但无法编辑模型,则它可以工作。有谁知道如何指定外键名称?

【问题讨论】:

    标签: entity-framework ef-code-first


    【解决方案1】:

    遵循命名约定将在上面创建正确的 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);
        }
    }
    

    【讨论】:

    • 感谢@Mark,您的解决方案非常适合上述示例。不幸的是,我需要一个似乎不起作用的第三个父子引用。如果您有时间,请查看我的最新问题,其中包含问题代码。 link
    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 2016-10-16
    • 1970-01-01
    • 2022-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多