context.Projects
.Include(x => x.Members) //List<Member> public class Member
.Include(x => x.Members.Select(z => z.City)) //public class City
.ToList();

中选择项目

包括项目列表。成员

包括每个项目。成员。城市

需要添加一些数据才能得出结果

context.Projects
.Include(x => x.Members)
.Include(x => x.Members.Select(z => z.City))
.Select(x => new {
    Project = x,
    Amount = 22
})
.ToList();

项目属性已填充,但成员为空

问题1-如何包含 Project。将新增为{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();

已填充项目属性,并已填充成员但已填充Members [0]。城市为空

问题2-如何填充成员[0]。城市

P.S.

Entity Framework 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; }
}

压力

这项工作-但代码开销

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,您将确保查询随后被执行,其余操作将在内存中完成:

context.Projects
       .Include(x => x.Members)
       .Include(x => x.Members.Select(z => z.City))
       .AsEnumerable()
       .Select(x => new { Project = x, Amount = 22 })
       .ToList();

关于c# - Linq EF Include()与Select()新类型丢失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36071987/

10-10 18:28