简体   繁体   中英

Entity Framework Core model with hierarchy of the same table

I use an ASP.NET Core Web API with .NET 5 and Entity Framework Core 5.

I have a table called Article with some properties, and I am struggling that the article could contain other articles. Like a hierarchy or some kind of "Bill of Materials".

I do not want to create extra tables like SubArticle because it could be nested multiple times.

I thought about of creating a mapping table ArticleHierarchy that is also used for M2M relations but with only one table, is this possible?

public class Article
{
    [Key]
    public int Id { get; set; }
    public string Name{ get; set; }        
    public string SomeProperties { get; set; } 

    public virtual ICollection<ArticleHierarchy> ArticleHierarchies { get; set; }           
}

public class ArticleHierarchy
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [ForeignKey(nameof(ParentArticle))]
    public int ArticleParentId { get; set; }
    [ForeignKey(nameof(ChildArticle))]
    public int ArticleChildId { get; set; }

    public virtual Article ParentArticle { get; set; }
    public virtual Article ChildArticle { get; set; }
}

Is this a way to go, and if so, how do my classes need to look like?

Or is there even a better way to do this?

Thanks

you have to fix relations, add

public class Article
{
    [Key]
    public int Id { get; set; }
    public string Name{ get; set; }        
    public string SomeProperties { get; set; } 

     public virtual ICollection<ArticleHierarchy> ParentArticleHierarchies { get; set;
    public virtual ICollection<ArticleHierarchy> ChilsArticleHierarchies { get; set; }           
}

public class ArticleHierarchy
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [ForeignKey(nameof(ParentArticle))]
    public int ArticleParentId { get; set; }
    [ForeignKey(nameof(ChildArticle))]
    public int ArticleChildId { get; set; }

    public virtual Article ParentArticle { get; set; }
    public virtual Article ChildArticle { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM