FK到同一个表代码第一个实体框架

时间:2015-04-08 13:40:50

标签: c# entity-framework ef-code-first

我是Entity Framework中Code-First方法的新手。我对如何做到这一点感到有点困惑:

我需要一个FK关系到同一个表,所以我可以有一个父 - >元素之间的子关系。

这是表格的模型:

public class BucketGroup
{
   public int Id {get;set;} // This is the PK in the Table

   public string Name {get;set;}


   // Now this the FK, to this Same Table:
  public int? BucketGroupId {get;set;}

}

所以我把这个项目设为Nullable,如果BucketGroupId为NULL,那么我知道它是父项。

我创建了一个测试项目并使用Database First,模型是这样的:

public partial class Testing
{
    public Testing()
    {
        this.Testing1 = new HashSet<Testing>();
    }

    public int Id { get; set; }
    public Nullable<int> ParentId { get; set; }

    public virtual ICollection<Testing> Testing1 { get; set; }
    public virtual Testing Testing2 { get; set; }
}

因此,如果我向我的模型中添加类似的属性,那么它会FK ID为PK吗?

public class BucketGroup
{
  public int Id {get;set;} // This is the PK in the Table

  public string Name {get;set;}


  // Now this the FK, to this Same Table:
  public int? BucketGroupId {get;set;}

  public virtual ICollection<BucketGroup> BucketGroup1 { get; set; }

}

这是对的吗?

1 个答案:

答案 0 :(得分:19)

您有两种选择:

  • 使用Data Annotations

    public class BucketGroup
    {
      public int Id {get;set;} 
    
      public string Name {get;set;}
    
      [ForeignKey("ParentBucketGroup")]
      public int? ParentBucketGroupId {get;set;}
    
      public virtual BucketGroup ParentBucketGroup {get;set;}
    
      public virtual ICollection<BucketGroup> Children { get; set; }
    }
    

    或者,使用Fluent Api

    public class BucketGroup
    {
      public int Id {get;set;} 
    
      public string Name {get;set;}
    
      public int? ParentBucketGroupId {get;set;}
    
      public virtual BucketGroup ParentBucketGroup {get;set;}
    
      public virtual ICollection<BucketGroup> Children { get; set; }
    }
    

    并且,要配置关系,您可以覆盖上下文中的OnModelCreating方法:

    modelbuilder.Entity<BucketGroup>().HasOptional(b=>b.ParentBucketGroup )
                                      .WithMany(b=>b.Children )
                                      .HasForeignKey(b=>b.ParentBucketGroupId);
    

更新

如果需要,您可以使用单向(也称为单向)关系,但您需要保留其中一个。

如果删除Children nav属性,则配置如下:

 modelbuilder.Entity<BucketGroup>().HasOptional(b=>b.ParentBucketGroup)
                                   .WithMany()
                                   .HasForeignKey(b=>b.ParentBucketGroupId);

或者,如果您删除ParentBuketGroup导航。属性,那么你需要这样做:

 modelbuilder.Entity<BucketGroup>().HasOptional()
                                   .WithMany(b=>b.Children)
                                   .HasForeignKey(b=>b.ParentBucketGroupId);
相关问题