linq 是否无法在并集中的投影内部使用Select?

lyr7nygr  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(161)
return await result.Select(student => new MarkSheetsStudentByIdDto
    {
        Id = student.RegId,
        FullName = student.FullName,
        AnnualMarkSheets = student.TermOne
        .Select(x => new MarkSheetDto
        {
            ...
            Comments = student.Comments.Where(x => x.StudentId.Equals(student.RegId)).Select(x => x.CommentText).ToList()
        }).Union(student.TermTwo
        .Select(x => new MarkSheetDto
        {
            ...
            Comments = student.Comments.Where(x => x.StudentId.Equals(student.RegId)).Select(x => x.CommentText).ToList()
        })).ToList()
    }).FirstOrDefaultAsync(cancellationToken);

对于上面的示例代码片段,我在运行时遇到此错误。
应用客户端投影后无法转换设置操作。请考虑将设置操作移到最后一个“select”调用之前。
如果我删除评论,它就不会发生。有人能指导我如何解决这个问题吗?

fhg3lkii

fhg3lkii1#

您必须执行客户端后处理。EF Core可以转换简单的Eager Loading查询。Union/Concat增加了额外的复杂性。

var rawResult = await result.Select(student => new 
    {
        Id = student.RegId,
        FullName = student.FullName,
        TermsOne = student.TermOne
          .Select(x => new MarkSheetDto
          {
              ...
              Comments = student.Comments.Where(x => x.StudentId.Equals(student.RegId)).Select(x => x.CommentText).ToList()
          }).ToList(),
        TermsTwo = student.TermTwo
          .Select(x => new MarkSheetDto
          {
              ...
              Comments = student.Comments.Where(x => x.StudentId.Equals(student.RegId)).Select(x => x.CommentText).ToList()
          }).ToList()
    }).FirstOrDefaultAsync(cancellationToken);

if (rawResult == null)
  return null;

return new MarkSheetsStudentByIdDto
{
    Id = rawResult.Id,
    FullName = rawResult.FullName,
    AnnualMarkSheets = rawResult.TermsOne.Concat(rawResult.TermsTwo).ToList()
};

相关问题