[英]Entity Framework Code First many to many for one entity
我有模特類別:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
我想創建一個新的模型DependencyCategory,像這樣來存儲多對多子代父關系。
public class DependencyCategory
{
public int Id { get; set; }
public Category Child { get; set; }
public Category Parent { get; set; }
}
如何在類別模型中與ICollection<DependencyCategory>
子代,父代現在創建關系? 例如,當我訪問父類別時,如果要查看所有子項,或者當子目錄中的所有父項都可用時,我想要。
根據我的理解,您的類應該這樣定義。
public class Category
{
public int Id {get; set; }
public string Name {get; set; }
public string Description {get; set; }
public List<Category> ParentCategories {get; set; }
public List<Category> ChildCategories {get; set; }
}
public class CategoryRelationships
{
public int ParentCategoryId {get; set; }
public int ChildCategoryId {get; set; }
}
我還沒有囊括所有內容,因為Code-First不是我的強項,但是它應該為您指明正確的方向並稍微改善您的數據庫結構。 請注意, CategoryRelationship
類定義了您的關系,在ParentCategoryId
和ChildCategoryId
上都放置了一個復合主鍵 ,並且您不需要單獨的Id列,同時還確保了相同的兩個ChildCategoryId
不能鏈接兩次。
希望能幫助到你。
HasRequired(a => a.ParentProduct)
.WithMany(b => b.ChildProducts)
.HasForeignKey(c => c.ParentId) // FK_RelatedProductParentID
.WillCascadeOnDelete(false);
HasRequired(a => a.ChildProduct)
.WithMany(b => b.ParentProducts)
.HasForeignKey(c => c.ChildId); // FK_RelatedProductChildID
public class CategoryDependency
{
[Key, Column(Order = 0)]
public int ParentId { get; set; } // ParentID
[Key, Column(Order = 1)]
public int ChildId { get; set; } // ChildID
// Foreign keys
public virtual Product ParentProduct { get; set; } // FK_RelatedProductParentID
public virtual Product ChildProduct { get; set; } // FK_RelatedProductChildID
}
public class Product
{
[Key]
public int ProductId { get; set; } // ProductID (Primary key)
public string ProductName { get; set; } // ProductName
// Reverse navigation
public virtual ICollection<RelatedProduct> ParentProducts { get; set; } // RelatedProduct.FK_RelatedProductChildID
public virtual ICollection<RelatedProduct> ChildProducts { get; set; } // RelatedProduct.FK_RelatedProductParentID
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.