【问题标题】:C# Entities Tree Model [closed]C# 实体树模型
【发布时间】:2020-05-25 17:54:03
【问题描述】:

在博客页面上, 子类别将链接到主类别,并且将是子类别的文章。你觉得模型结构正确吗?

我将使用 Asp.net Core 和 EntityFrameworkCore 架构进行开发。

public class Category
{
    public int Id { get; set; }

    public string CategoryName { get; set; }


    public bool IsActive { get; set; }

    public ICollection<SubCategory> SubCategories { get; set; }
}
--------------------------------------
public class SubCategory
{
    public int Id { get; set; }

    public string SubCategoryName { get; set; }


    public bool IsActive { get; set; }

    public int CategoryId { get; set; }

    public virtual Category Category { get; set; }

    public virtual ICollection<Article> Articles { get; set; }
}
----------------------------------------------
public class Article
{
    public int Id { get; set;}

    public string ArticleTitle { get; set; }

    public string ArticleContent { get; set; }

    public DateTime PublishDate { get; set; }

    public int AuthorId { get; set; }
    public virtual Author Author { get; set; }

    public int SubCategoryId { get; set; }
    public virtual SubCategory SubCategory { get; set; }
}

【问题讨论】:

    标签: c# entity-framework asp.net-core model tree


    【解决方案1】:

    另一种方法是将类别模型更改为Self-referencing relationship

    这些链接对Self-referencing 很有帮助 1 , 2

    public class Category
    {
        public int Id { get; set; }
    
        public string CategoryName { get; set; }
        public int? ParentId { get; set; }
    
        public bool IsActive { get; set; }
        public Category Parent { get; set; }
        public ICollection<Category> SubCategories { get; set; }
        public ICollection<ArticleCategories> ArticleCategories { get; set; }
    }
    

    然后在ArticleCategory类之间创建Many-to-Many关系

    public class ArticleCategories
    {
        public int ArticleId { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
        public Article Article { get; set; }
    }
    

    文章型号

    public class Article
    {
        public int Id { get; set;}
    
        public string ArticleTitle { get; set; }
    
        public string ArticleContent { get; set; }
    
        public DateTime PublishDate { get; set; }
    
        public int AuthorId { get; set; }
        public virtual Author Author { get; set; }
    
        public ICollection<ArticleCategories> ArticleCategories { get; set; }
    }
    

    在这种情况下,任何Article 可以有多个Category,任何Category 可以用于多个Articles

    【讨论】:

    • 谢谢我试试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2022-07-26
    • 1970-01-01
    相关资源
    最近更新 更多