[英]Include Entities to Child Collection With Filter Linq EF5
I have a problem while filtering a child collection, the filtration is done but i need to include extra entities to the collection, i don't know how to do that 我在过滤子集合时遇到问题,过滤已完成,但是我需要在集合中包括其他实体,我不知道该怎么做
I have an entity Employee 我有实体员工
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public string EmpNum { get; set; }
public virtual ICollection<EmployeeProfile> EmployeeProfiles { get; set; }
}
and the collection entity EmployeeProfile 和集合实体EmployeeProfile
public class EmployeeProfile
{
[Key]
public int EmployeeProfileId { get; set; }
[ForeignKey("Employee")]
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
[ForeignKey("Nationality")]
public int? NationalityId{ get; set; }
....
public DateTime? UpdateDatetime { get; set; }
public virtual Nationality Nationality{ get; set; }
public virtual Employee Employee { get; set; }
}
i used projection to filter 我用投影来过滤
var employees = context.Employees
.Include(e => e.EmployeeProfiles)
.Include(e => e.EmployeeProfiles.Select(a => a.Nationality))
.Select(e => new EmployeeLeatestProfileModel
{
EmployeeId = e.EmployeeId
,
EmpNum = e.EmpNum
,
LastUpdatedProfile = e.EmployeeProfiles
.Where(p => p.EmployeeId == e.EmployeeId)
.OrderByDescending(a => a.UpdateDatetime).Take(1)
});
and this is the result model 这就是结果模型
public class EmployeeLeatestProfileModel {
public int EmployeeId { get; set; }
public string EmpNum { get; set; }
public IEnumerable<EmployeeProfile> LastUpdatedProfile;
}
the thing is when i am trying to fetch the Nationality i didn't find the data of it which seems like it is not included in the query!! 事情是当我尝试获取国籍时,我没有找到它的数据,这似乎不包含在查询中!!
so what can i do to include the Nationality entity or aany other entities for the child collection EmoployeeProfile 所以我该怎么做才能为孩子集合EmoployeeProfile包括国籍实体或其他任何实体
and i am not using Lazy Loading by the way 而且我没有使用延迟加载
Instead of using projection you could use the object query include passing in a string. 代替使用投影,您可以使用对象查询包括传递一个字符串。
https://msdn.microsoft.com/en-us/library/bb738708(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/bb738708(v=vs.110).aspx
.Include(e => e.EmployeeProfiles)
.Include("EmployeeProfiles.Nationality")
.Include("EmployeeProfiles.Employee")
Haven't tested this but try selecting into an anonymous collection. 尚未对此进行测试,但请尝试选择一个匿名集合。
var employees = context.Employees
.Select(e => new
{
Employee = e,
EmployeeProfiles = e.EmployeeProfiles,
Nationalities = e.EmployeeProfiles.Select(a => a.Nationality)
})
.ToList() // do this to force the projection
.Select(e => new EmployeeLeatestProfileModel
{
EmployeeId = e.Employee.EmployeeId,
EmpNum = e.Employee.EmpNum,
LastUpdatedProfile = e.EmployeeProfiles
.Where(p => p.EmployeeId == e.Employee.EmployeeId)
.OrderByDescending(a => a.UpdateDatetime)
.Take(1)
})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.