LINQ查询语法转方法语法(多对多关联场景)
LINQ查询语法转方法语法实现
问题背景
需要将下述使用查询语法编写的LINQ语句,转换为等价的方法语法实现。转换过程中,Classes表用于和Students表建立多对多关系的导航属性ICollection<Student> Students是造成转换困难的核心原因。
待转换的原始查询语法代码:
from exa in _context.Exams from stu in exa.Class.Students where exa.Id == 1 select new StudentFullName { Id = stu.Id, FullName = stu.Person.FirstName + " " + stu.Person.LastName }
错误尝试
最初编写的转换代码如下:
_context.Exams .Where(exa => exa.Id == id) .Select(exa => new StudentFullName { Id = exa.Class.Students.Select(stu => stu.Id), FullNamee = exa.Class.Students.Select(stu => stu.Person.FirstName + " " + stu.Person.LastName) }).ToList();
该写法无法得到预期结果:对Students集合嵌套调用Select会返回集合类型值,最终投影出的Id属性类型为IEnumerable<int>,和预期的int类型不匹配,无法正确构造StudentFullName实例。
正确实现
核心转换规则:查询语法中用于遍历外层元素包含的子集合的多重from子句,对应方法语法中的SelectMany运算符,而非嵌套Select。
调整后可正常运行的代码如下:
_context.Exams .Where(exa => exa.Id == id) .SelectMany(exa => exa.Class.Students .Select(stu => new StudentFullNameViewModel { Id = stu.Id, FullName = stu.Person.FirstName + " " + stu.Person.LastName }) ).ToList()
SelectMany会将每个Exam对应班级下的所有学生集合打平为一维序列,逐个投影为学生姓名信息对象,最终返回结果和原始查询语法完全一致。
内容的提问来源于stack exchange,提问作者Mazzmax
相关产品推荐
相关产品推荐

