gpt4 book ai didi

c# - Linq EF Include() with Select() new type lost included

转载 作者:太空狗 更新时间:2023-10-29 22:15:46 24 4
gpt4 key购买 nike

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();

Project 属性已填充,但 Members 为空

问题 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();

Project 属性已填充,Members 已填充,但 Members[0].City 为空

问题2——如何填写Members[0].City

附言

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() with Select() new type lost included,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36071987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com