首页 文章

将多实体连接到单个模型实体框架代码优先

提问于
浏览
0

我有这些表:

Category

CategoryId
CategoryTitle
...........
ICollection<Article> Articles

每个类别可以有几篇文章:

Article

ArticleId
ArticleTitle  
NumberOfComment
NumberOfView

ICollection<ArticleReview> Reviews

并且每篇文章都有一些用户的评论:

ArticleReview

ArticleReviewId 
ReviewPoint
ArticleId { get; set; }
public string ReviewerId { get; set; }

这是我的ExcelExport类:

public class excelExport 
{
        public string ArticleTitle { get; set; }

        public int NumberOfComment { get; set; }
        public int NumberOfReviews { get; set; }
        public List<ResearchReviewReport> Reviews { get; set; }
}

public class ArticleReviewReport
{
        public string Reviewer { get; set; }
        public int ReviewPoint { get; set; }
}

Note :因为文章评论的数量不同,我使用一对多关系,但在最终结果中,所有一对多应该在单行中展平:
现在我创建一个不属于数据库的新类,并将此类传递给 ExcelPackage 类以生成xlsx输出:

ExcelExport

ArticleTitle 
Reviewer1Point
Reviewer2Point
............
ReviewerNPoint
ReviewersAvaragePoint
NumberOfComment
NumberOfView

如何填充 excelExport 类使用另外3个类?

注意 excelExport

1 回答

  • 1

    假设您有以下型号:

    public class Category
    {
        public long CategoryId { get; set; }
        public string CategoryTitle { get; set; }
        public virtual ICollection<Article> Articles { get; set; }
    }
    
    public class Article
    {
        public long ArticleId { get; set; }
        public long CategoryId { get; set; }
        public string ArticleTitle { get; set; }
        public int NumberOfComment { get; set; }
        public int NumberOfView { get; set; }
        public virtual Category Category { get; set; }
        public virtual ICollection<ArticleReview> Reviews { get; set; }
    }
    public class ArticleReview
    {
        public long ArticleReviewId { get; set; }
        public long ArticleId { get; set; }
        public string ReviewerId { get; set; }
        public int ReviewPoint { get; set; }
        public virtual Article Article { get; set; }
    }
    public class ExcelExport
    {
        public string ArticleTitle { get; set; }
        public int NumberOfComment { get; set; }
        public int NumberOfReviews { get; set; }
        public List<ArticleReviewReport> Reviews { get; set; }
    }
    
    public class ArticleReviewReport
    {
        public string Reviewer { get; set; }
        public int ReviewPoint { get; set; }
    }
    

    最终你将有 ExcelExport 的列表,查询应该是这样的( _context 是你的实体DbContext的一个实例):

    public List<ExcelExport> GetExcelExports()
    {
        return _context.Articles.Select(a => new ExcelExport
        {
            ArticleTitle = a.ArticleTitle,
            NumberOfComment = a.NumberOfComment,
            NumberOfReviews = a.NumberOfView,
            Reviews = a.Reviews.Select(r => new ArticleReviewReport
            {
                Reviewer = r.ReviewerId,
                ReviewPoint = r.ReviewPoint
            }).ToList()
        }).ToList();
    }
    

相关问题