代码优先外键配置

时间:2012-08-21 20:04:02

标签: entity-framework

我很难维护父类和它的孩子之间的多种关系。谁能告诉我为什么我可以在父母中创建两个子引用而不是第三个?以下代码仅在第三个引用被注释掉时才有效。

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Child1Id { get; set; }
    public Child Child1 { get; set; }
    public int Child2Id { get; set; }
    public Child Child2 { get; set; }
    //public int Child3Id { get; set; }
    public Child Child3 { 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; }

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

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

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

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试从Parent到Child实体建立一对多关系。在这种情况下,代码应如下所示:

public class Parent
{
    public int Id { get; set; }
    public string Name { 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; }
}

只要您遵循有关命名导航属性和外键的默认约定,就不必在Fluent API中指定关系。您将必须使用Fluent API和/或属性来配置您使用非约定名称的关系,例如,重命名ParentId需要您在[ForeignKey(“Parent”)]属性上标记它。

使用Fluent API的最常见用例是禁用级联删除(无法使用属性执行此操作)。

相关问题