对EF的Linq查询,Include()被只包含where子句的查询忽略
本文关键字:查询 包含 where 子句 Linq EF Include | 更新日期: 2023-09-27 17:59:50
我的BLL中有以下代码,可以通过WCF服务调用访问:
public List<Dispatch> GetDispatchesByDateRange(DateTime start, DateTime end, params string[] includes)
{
MyEntities entities = new MyEntities();
var res = from d in entities.Dispatches
where d.Route.Legs.Any(x =>
x.StartPoint.ArrivalTime >= start && x.StartPoint.ArrivalTime <= end ||
x.StartPoint.DepartureTime >= start && x.StartPoint.DepartureTime <= end ||
x.EndPoint.ArrivalTime >= start && x.EndPoint.ArrivalTime <= end ||
x.EndPoint.DepartureTime >= start && x.EndPoint.DepartureTime <= end)
select d;
ObjectQuery<Dispatch> query = res as ObjectQuery<Dispatch>;
foreach (string s in includes)
query.Include(s);
return query.ToList();
}
来自客户端的一个调用将一些include一起发送到与急切加载相关的实体。我遇到的问题是Includes被忽略了。我读过EF在子查询中或作为投影的一部分使用时会忽略includes。在这种情况下,我不做这两件事,只是根据where条件选择整个实体,然后添加includes。如果我不使用where条件,includes会显示得很好。有没有其他人遇到过这种情况,简单地添加一个where条件导致include被忽略?这可能是因为我对关系层次结构的"哪里"挖掘得太深了吗?
您可以尝试在Where()之前调用Include扩展方法。
在EF 5中,它可以作为进行
DbQuery<Dispatch> query = entities.Dispatches;
foreach (var include in includes)
{
query = query.Include(include);
}
var res = from d in dispatches
where ...
select d;
终于成功了,不得不使用这个公式:
ObjectQuery<Dispatch> query = (from item in entities.Dispatches select item) as ObjectQuery<Dispatch>;
foreach (string s in includes)
query = query.Include(s);
var res = from d in query
where d.Route.Legs.Any(x =>
x.StartPoint.ArrivalTime >= start && x.StartPoint.ArrivalTime <= end ||
x.StartPoint.DepartureTime >= start && x.StartPoint.DepartureTime <= end ||
x.EndPoint.ArrivalTime >= start && x.EndPoint.ArrivalTime <= end ||
x.EndPoint.DepartureTime >= start && x.EndPoint.DepartureTime <= end)
select d;
从本质上讲,主要的区别在于,我正在执行一个初始的linq查询,然后附加includes,最后使用where条件从该组中重新选择。
我也遇到了同样的问题,EF无故忽略了Include()
。我通过使用子查询解决了这个问题。不是最好的解决方案,但找不到另一个有效的解决方案。。。下面的代码段。编辑:你可能也可以用加入来代替它,没有时间测试它。
注意:在撰写本文时,我正在使用EF Core RC1(不是我的决定)
var result = projs.Select(p => new FoundProject
{
ProjectId = p.Id,
ProjectName = p.Name,
ProjectEntityTypeId = p.ProjectEntityTypeId,
ProjectEntityType = context.ProjectEntityTypes.Where(e => e.Id == p.ProjectEntityTypeId).Select(e => e.Name).FirstOrDefault(),
RentStatus = p.RentStatus,
RentPrice = p.RentPrice
});