分组依据包括(内部连接)

Group by with include (inner join)

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

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

 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, 问题:[ 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; }
    }

您应该使用带有大部分参数的 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()
    });