繁体   English   中英

在EF上的Linq查询,仅包含where子句的查询将忽略Include()

[英]Linq query on EF, Include() is ignored with a query that only contains a where clause

我的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();
}

来自客户端的呼叫之一发送一些包含,以渴望与负载相关的实体。 我遇到的问题是忽略了Includes。 我已经读到EF在子查询中或作为投影的一部分使用时将忽略包含。 在这种情况下,我不会执行任何操作,只是根据where条件选择整个实体,然后附加包含。 如果我不使用where条件,那么包含就很好了。 还有其他人遇到过这样的情况吗?只是添加一个where条件导致包括被忽略? 可能是因为我的“位置”太深了关系层次吗?

您可以尝试在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查询,然后附加包含,最后使用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
                });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM