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
的列表包括 project.Members.City
中的每一个需要向结果中添加一些数据
context.Projects
.Include(x => x.Members)
.Include(x => x.Members.Select(z => z.City))
.Select(x => new {
Project = x,
Amount = 22
})
.ToList();
已填充项目属性,但成员为空
问题1 - 如何将 Project.Members 包含在 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] .City为空
问题2 - 如何填写会员[0]。城市
P.S。
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
这项工作 - 但代码开销
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();
答案 0 :(得分:10)
在include之后执行的任何操作(过滤除外)都将导致包含被丢弃。通过在包含之后调用AsEnumerable
,您将确保执行查询,其余操作将在内存中完成:
context.Projects
.Include(x => x.Members)
.Include(x => x.Members.Select(z => z.City))
.AsEnumerable()
.Select(x => new { Project = x, Amount = 22 })
.ToList();
答案 1 :(得分:0)
将您的导航属性声明为虚拟,列为ICollection,并在为实体保湿时让EF替换为其具体实现:
.ogg