Home > Enterprise >  Entity Framework Core model with hierarchy of the same table
Entity Framework Core model with hierarchy of the same table

Time:11-29

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

CodePudding user response:

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


    [InverseProperty(nameof(ArticleHierarchy.ChildArticle))]
    public virtual ICollection<ArticleHierarchy> ChildArticleHierarchies { get; set; }    

    [InverseProperty(nameof(ArticleHierarchy.ParentArticle))]
     public virtual ICollection<ArticleHierarchy> ParentArticleHierarchies { get; set;}
       
}

public class ArticleHierarchy
{
    [Key]
    public int Id { get; set; }
   
    public int ArticleParentId { get; set; }
 
    public int ArticleChildId { get; set; }

    [ForeignKey(nameof(ParentArticleId))]
    [InverseProperty("ParentArticleHierarchies")]
    public virtual Article ParentArticle { get; set; }

    [ForeignKey(nameof(ChildArticleId))]
    [InverseProperty("ChildArticleHierarchies")]
    public virtual Article ChildArticle { get; set; }
}
  • Related