[英]FK to the Same Table Code First Entity Framework
我是Entity Framework中Code-First方法的新手。 我對如何做到這一點感到有點困惑:
我需要一個FK關系到同一個表,所以我可以在元素之間有一個Parent - > Child關系。
這是表的模型:
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;}
}
所以我把這個項目BucketGroupId
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; }
}
那么如果我向我的模型添加一個類似的屬性會使它成為PK
Id的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;}
public virtual ICollection<BucketGroup> BucketGroup1 { get; set; }
}
它是否正確?
您有兩種選擇:
使用數據注釋 :
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.