按包含(内部联接)分组

时间:2019-07-30 21:38:06

标签: c# asp.net database linq iqueryable

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

enter image description here

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

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

1 个答案:

答案 0 :(得分:0)

您应该使用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()
    });
相关问题