重写ef core 2.1中的相关子查询

时间:2018-10-20 16:50:28

标签: c# ef-core-2.1

有没有一种方法可以重写此查询,使其不是相关的子查询?

var query = (from o in dbcontext.Orders
                             let lastStatus = o.OrderStatus.Where(x => x.OrderId == o.Id).OrderByDescending(x => x.CreatedDate).FirstOrDefault()
                             where lastStatus.OrderId != 1
                             select new { o.Name, lastStatus.Id }
                             ).ToList();

结果是:

 SELECT [o].[Name], (
          SELECT TOP(1) [x0].[Id]
          FROM [OrderStatus] AS [x0]
          WHERE ([x0].[OrderId] = [o].[Id]) AND ([o].[Id] = [x0].[OrderId])
          ORDER BY [x0].[CreatedDate] DESC
      ) AS [Id]
      FROM [Orders] AS [o]
      WHERE (
          SELECT TOP(1) [x].[OrderId]
          FROM [OrderStatus] AS [x]
          WHERE ([x].[OrderId] = [o].[Id]) AND ([o].[Id] = [x].[OrderId])
          ORDER BY [x].[CreatedDate] DESC
      ) <> 1

我已经厌倦了在子查询上进行联接,但是EF 2.1正在执行有线操作……这不是我期望的;

     var query = (from o in dbcontext.Orders
                     join lastStat in (from os in dbcontext.OrderStatus
                                       orderby os.CreatedDate descending
                                       select new { os }
                                       ) on o.Id equals lastStat.os.OrderId
                     where lastStat.os.StatusId != 1
                     select new { o.Name, lastStat.os.StatusId }).ToList();

2 个答案:

答案 0 :(得分:2)

在EF6替换中

let x = (...).FirstOrDefault()

使用

from x in (...).Take(1).DefaultIfEmpty()

通常会生成更好的SQL。

所以通常我会建议

var query = (from o in db.Set<Order>()
             from lastStatus in o.OrderStatus
                 .OrderByDescending(s => s.CreatedDate)
                 .Take(1)
             where lastStatus.Id != 1
             select new { o.Name, StatusId = lastStatus.Id }
            ).ToList();

(不需要DefaultIfEmpty(左联接),因为where条件将使其变成内部联接)。

不幸的是,当前(EF Core 2.1.4)存在翻译问题,因此上述内容导致客户评估。

当前解决方法是将导航属性访问器o.OrderStatus替换为相关子查询:

var query = (from o in db.Set<Order>()
             from lastStatus in db.Set<OrderStatus>()
                 .Where(s => o.Id == s.OrderId)
                 .OrderByDescending(s => s.CreatedDate)
                 .Take(1)
             where lastStatus.Id != 1
             select new { o.Name, StatusId = lastStatus.Id }
            ).ToList();

为SqlServer数据库(横向连接)生成以下SQL:

  SELECT [o].[Name], [t].[Id] AS [StatusId]
  FROM [Orders] AS [o]
  CROSS APPLY (
      SELECT TOP(1) [s].*
      FROM [OrderStatus] AS [s]
      WHERE [s].[OrderId] = [o].[Id]
      ORDER BY [s].[CreatedDate] DESC
  ) AS [t]
  WHERE [t].[Id] <> 1 

答案 1 :(得分:0)

我将假设您实际上是在获取所有Order,但仅获取其中一部分(一页或一批要处理)。

在这种情况下,最好将其拆分为两个查询(尽管未测试):

var orders = dbcontext.Orders.Where(o => /* some filter logic */);
var orderIds = orders.Select(o => o.OrderId).ToList();

// get status for latest change - this should query OrderStatus only
var statusNameMap = dbContext.OrderStatus
   .Where(os => orderIds.Contains(Id))
   .GroupBy(os => os.OrderId)
   .Select(grp => grp.OrderByDescending(grp => grp.CreatedDate).First())
   .ToDictionary(os => os.OrderId, os => os.StatusId);

// aggregate the results
// the orders might fetch only the needed columns to have less data on the wire
var result = orders.
    .ToList()
    .Select(o => new { o.Name, statusNameMap[o.OrderId] });

我认为查询不会更好,但是可能更容易理解这里发生的情况。

如果确实需要处理所有Order,并且有很多(或许多Status),则可以考虑直接在{{1}中维护一个LastStatusId列}表(状态更改时应更新此表)。