c# - 分组方式包括(内部连接)
问题描述
我正在查询由下图中的其他两个表生成的表。在一个类别中,我可以有几个问题。
使用此查询没有得到我预期的结果:
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; }
}
解决方案
您应该使用带有大部分参数的 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()
});
推荐阅读
- flowtype - Flow 类型声明中的省略号有什么作用?
- php - 将复选框标签链接到另一个并在发布时区分
- java - 当我尝试从面板中删除形状时,Java repaint() 方法不起作用
- javascript - Javascript str.split(/[^a-zA-Z0-9.@]|(username|fname)/ 不从字符串中删除 'username' 或 'fname'
- pandas - KeyError:“[索引(['',''],dtype ='object')]都没有在[columns]中”尝试选择dask数据帧上的列
- google-chrome-devtools - 单击链接弹出新的下载选项卡并立即关闭时,如何在 chrom devtools 中捕获网络信息?
- python - 用标签转置日期时间
- javascript - 从 .txt 文件读取并显示数据的 React 组件
- reactjs - 尝试导入错误:“更新”未从“@createjs/tweenjs”导出(导入为“TWEEN”)
- string - 使用不正确的字符串格式时如何从编译器获取消息