首页 > 解决方案 > linq中的动态投影与fieldNames列表

问题描述

我想对我的集合的字段和每个实体中的嵌套集合进行投影,我使用 EntityFramework 6.2 我已经通过动态查询来做到这一点,例如下面的代码

Students.Select("new (Name,Family,new(Category.Name) as Category)");

它有效,但是当我想对集合执行此操作时,它会抛出错误

  Students.Select("new (Name,Family,new(Courses.Name,Courses.UnitName) as Courses)");

我想要,它返回结果,因为下面的代码返回

Students.Select(std=>new{
 std.Name, 
 Category=new{std.Category.Name},
 Courses=std.Courses.Select(co=>new{
  co.Name,co.UnitName
})}) ;

如果您有任何想法,请与我分享

标签: c#entity-frameworklinqentity-framework-6dynamic-linq

解决方案


你不能用System.Linq.Dynamic. System.Linq.Dynamic.Core(库的更高级的分支)是可能的。

相当于您以非动态方式编写的查询:

var q = Students.Select("new (Name, Category.Name as Category, Courses.Select(new (Name, UnitName)) as Courses)");

你要找的只是Courses.Select(new (field1, field2)) as SomeAlias


推荐阅读