Linq EF Include()与Select()新类型丢失 [英] Linq EF Include() with Select() new type lost included
问题描述
context.Projects
.Include(x => x.Members) //List<Member> public class Member
.Include(x => x.Members.Select(z => z.City)) //public class City
.ToList();
从项目
包括项目的列表.成员
包括每个 project.Members.City
需要向结果中添加一些数据
Need add some data to result
context.Projects
.Include(x => x.Members)
.Include(x => x.Members.Select(z => z.City))
.Select(x => new {
Project = x,
Amount = 22
})
.ToList();
项目属性已填充,但成员为空
问题1-如何在 new {Project = x}
我下一步
context.Projects
.Include(x => x.Members) //List<Member>
.Include(x => x.Members.Select(z => z.City)) //City is navigation property
.Select(x => new {
Project = x,
Members = x.Members,
Amount = 22
})
.ToList();
项目属性已填充,成员已填充,但成员[0].城市为空
Project properties is filled and Members is filled but Members[0].City is null
问题2-如何填充成员[0].城市
Question 2 - how fill Members[0].City
P.S.
EntityFramework 6
EntityFramework 6
public class Project
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ProjectMember> Members { get; set; }
}
public class ProjectMember
{
public Guid ProjectId { get; set; }
public Project Project { get; set; }
public Guid CityId { get; set; }
public City City { get; set; }
}
P.S.S
这项工作-但有代码开销
This work - but code overhead
context.Projects
.Include(x => x.Members) //List<Member>
.Include(x => x.Members.Select(z => z.City)) //City is navigation property
.Select(x => new {
Project = x,
Members = x.Members.Select(z => new {
Item = z,
City= z.City
}).ToList(),
Amount = 22
})
.ToList();
推荐答案
在包含之后(过滤除外)您执行的任何操作都将导致包含被丢弃.通过在包含之后调用AsEnumerable
,您将确保查询随后被执行,其余操作将在内存中完成:
Any operations you do after the includes (except for filtering) will cause the includes to be discarded. By calling AsEnumerable
after the includes, you will make sure the query gets executed then and the rest of the operations will be done in memory:
context.Projects
.Include(x => x.Members)
.Include(x => x.Members.Select(z => z.City))
.AsEnumerable()
.Select(x => new { Project = x, Amount = 22 })
.ToList();
这篇关于Linq EF Include()与Select()新类型丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!