首页 > 解决方案 > 分组方式包括(内部连接)

问题描述

我正在查询由下图中的其他两个表生成的表。在一个类别中,我可以有几个问题。

在此处输入图像描述

使用此查询没有得到我预期的结果:

 var result = await _repository.GetQuestionCategory()
                 .Include(x => x.Category)
                 .Include(y => y.Question)
                 .Select(x => new QuestionCategoryViewModel
                 {
                     Id = x.Id,
                     CategoryId = x.Category.Id,
                     CategoryName = x.Category.Name,
                     IsRequired = x.IsRequired,
                     QuestionId = x.Question.Id,
                     QuestionName = x.Question.Name,
                     Weigth = x.Weigth
                 }).GroupBy(x => x.CategoryId).ToListAsync().ConfigureAwait(false);

我怎么能发送类似这样的结构

{ categoryId, categoryName, IsRiquered, Weigth, questions: [ questionId: questionName: y]}

Mmodel 类别和问题

    public class QuestionCategory
    {
		public Guid Id { get; set; }
		public Question Question { get; set;}
		public Category Category { get; set;}
		public int QuestionId { get; set; }
		public int CategoryId { get; set; }
        public bool IsRequired { get; set; }
		public int Weigth { get; set; }
    }

标签: c#asp.netdatabaselinqiqueryable

解决方案


您应该使用带有大部分参数的 GroupBy 语句。请注意,结果属性的不一致命名取自问题 1:1。您可能想要创建一些显式的 DTO 类型,而不是将结果创建为匿名类型。

IQueryable<QuestionCategory> questionCategories = new EnumerableQuery<QuestionCategory>(Enumerable.Empty<QuestionCategory>());

var result = questionCategories.GroupBy(
    // key selector
    qc => new
    {
        categoryId = qc.CategoryId,
        categoryName = qc.Category.Name,
        IsRiquered = qc.IsRequired,
        Weigth = qc.Weigth
    },
    // element selector
    qc => qc.Question,
    // result selector
    (k, v) => new
    {
        k.categoryId,
        k.categoryName,
        k.IsRiquered,
        k.Weigth,
        questions = v.Select(q => new {questionId = q.Id, questionName = q.Name}).ToList()
    });

推荐阅读