C# 过滤子实体LINQ方法
考虑以下查询:C# 过滤子实体LINQ方法,c#,silverlight-4.0,linq-to-entities,ria,C#,Silverlight 4.0,Linq To Entities,Ria,考虑以下查询: IQueryable<Employee> ret = this.ObjectContext.Employees .Include("EmployeeInformation") .Include("LatestInformation") .Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1); 因此,问题是如何过滤L
IQueryable<Employee> ret = this.ObjectContext.Employees
.Include("EmployeeInformation")
.Include("LatestInformation")
.Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);
因此,问题是如何过滤LatestInformation实体?如果从Employee到LatestInformation没有导航属性,请以另一种方式查询它。比如:
var ret = this.ObjectContext.LatestInfomration
.Where(i => i.Employee != null && i.year == 2015)
.Select(i => i.Employee)
.Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);
编辑以匹配以下OP注释:
你所说的导航属性是什么意思 如果它是某个唯一的id,那么您可以使用
List<int> latest = this.ObjectContext.LatestInformation.Select(lat=> lat.someid).ToList();
ret = ret.Where(r=> latest.Contains(ret.id)).Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);
我知道,但查询的目的是从员工那里获取数据,以及其他可能存在或不存在的数据。实际上,如果我使用这种方法,我应该以某种方式将查询作为左连接,以满足我的需要。。我说的对吗?@Alex你的意思是你也想要没有任何最新信息输入的员工吗?是的,这就是我需要的。@Alex我更新了我的答案。你的问题也应该如此。
// Extract needed data:
var employeeIdListWithInfo = this.ObjectContext.LatestInfomration
.Where(i => i.Employee != null)
.Select(i => i.Employee.Id)
.ToList();
// Build the query (not executed yet)
var employeeWithInformation = this.ObjectContext.LatestInfomration
.Where(i => i.Employee != null && i.year == 2015)
.Select(i => i.Employee)
.Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);
var lonelyEmployees = this.ObjectContext.Employee
.Where(emp => !employeeIdListWithInfo.Contains(emp.Id));
var ret = employeeWithInformation.Union(lonelyEmployees);
List<int> latest = this.ObjectContext.LatestInformation.Select(lat=> lat.someid).ToList();
ret = ret.Where(r=> latest.Contains(ret.id)).Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);