我在过滤子集合时遇到问题,过滤完成但我需要在集合中包含额外的实体,我不知道该怎么做
我有一个实体员工
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public string EmpNum { get; set; }
public virtual ICollection<EmployeeProfile> EmployeeProfiles { get; set; }
}
和集合实体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; }
}
我用投影来过滤
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)
});
这是结果模型
public class EmployeeLeatestProfileModel {
public int EmployeeId { get; set; }
public string EmpNum { get; set; }
public IEnumerable<EmployeeProfile> LastUpdatedProfile;
}
事情就是当我试图获取国籍时我没有找到它的数据,似乎它不包含在查询中!!
那么我该怎样做才能将国籍实体或其他任何实体包括在子集合中EmoployeeProfile
我并没有使用Lazy Loading
答案 0 :(得分:0)
您可以使用对象查询包括传入字符串,而不是使用投影。
https://msdn.microsoft.com/en-us/library/bb738708(v=vs.110).aspx
.Include(e => e.EmployeeProfiles)
.Include("EmployeeProfiles.Nationality")
.Include("EmployeeProfiles.Employee")
Haven未对此进行测试,但尝试选择匿名收藏。
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();