2014-02-19 188 views
0

我有模型类别:实体框架代码优先多对多的一个实体

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>儿童分类模型的关系,家长?例如,当我想要访问类别父级以查看所有子级或者是否是子级时,查看所有可用的父级。

回答

0

根据我的理解,你的类应该像这样定义。

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

我没有包括所有的管道作为代码首先是不是我的强项,但它应该指向你在正确的方向和稍微改善你的数据库结构。请注意,CategoryRelationship类定义了您的关系,在ParentCategoryIdChildCategoryId上都放置了一个复合主键,并且您不需要单独的Id列,同时还确保相同的两个类别不能链接两次。

希望它有帮助。

+0

好是很好的方式,但现在首先如何设置新表和列名的名称,因为它们是自动生成的?如何避免循环引用? – user2297114

+0

@ user2297114对不起,我不完全确定你的意思。什么是自动生成的,什么循环引用需要避免? –

+0

我只使用Category类型并生成具有列Category_Id Category_Id1的表CategoryCategories。并在此表中,如果我有这样的东西[5 \t 6] [5 \t 4] [4 \t 6]当获得一个类别我有循环引用。对于孩子,我有父母也有孩子。我想避免这种情况。 – user2297114

0

This solved

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 
    } 
相关问题