EF Core 2.1进行多个数据库调用?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (882)

有没有办法阻止EF Core在单个枚举函数调用上进行多次DB往返?

考虑这个相对简单的LINQ表达式:

var query2 = context.CheckinTablets.Select(ct => new
            {
                Id = ct.Id,
                DeviceName = ct.Name,
                Status = ct.CheckinTabletStatuses
                    .OrderByDescending(cts => cts.TimestampUtc).FirstOrDefault()
            }).ToList();

在过去,expactation是“一个枚举调用转换为一个DB调用”(如果禁用延迟加载)。在EF Core中已不再是这种情况!

在EF 6.2.0中,这个LINQ被翻译成

SELECT [Extent1].[CheckinTabletID] AS [CheckinTabletID],
   [Limit1].[TimestampUtc] AS [TimestampUtc]
  --...
FROM [dbo].[CheckinTablet] AS [Extent1] OUTER APPLY (
SELECT TOP (1) [Project1].[CheckinTabletStatusID] AS [CheckinTabletStatusID],
               [Project1].[CheckinTabletID] AS [CheckinTabletID],
               [Project1].[TimestampUtc] AS [TimestampUtc]
FROM (
SELECT [Extent2].[CheckinTabletStatusID] AS [CheckinTabletStatusID],
       [Extent2].[CheckinTabletID] AS [CheckinTabletID],
       [Extent2].[TimestampUtc] AS [TimestampUtc]
     --...
FROM [dbo].[CheckinTabletStatus] AS [Extent2]
WHERE [Extent1].[CheckinTabletID] = [Extent2].[CheckinTabletID]
) AS [Project1] ORDER BY [Project1].[TimestampUtc] DESC
) AS [Limit1];

虽然非常丑陋,但是它非常适合POLA。更重要的是,我们可以使用它来优化数据库端(索引)。

使用EF Core 2.1.0,我们得到这样的结果:

SELECT [ct].[CheckinTabletID] AS [Id], [ct].[strName] AS [DeviceName] FROM [CheckinTablet] AS [ct]

exec sp_executesql N'SELECT TOP(1) [cts].[CheckinTabletStatusID], [cts].[CheckinTabletID], [cts].[TimestampUtc] FROM [CheckinTabletStatus] AS [cts] WHERE @_outer_Id = [cts].[CheckinTabletID] ORDER BY [cts].[TimestampUtc] DESC',N'@_outer_Id int',@_outer_Id=1

exec sp_executesql N'SELECT TOP(1) [cts].[CheckinTabletStatusID], [cts].[CheckinTabletID], [cts].[TimestampUtc] FROM [CheckinTabletStatus] AS [cts] WHERE @_outer_Id = [cts].[CheckinTabletID] ORDER BY [cts].[TimestampUtc] DESC',N'@_outer_Id int',@_outer_Id=2

exec sp_executesql N'SELECT TOP(1) [cts].[CheckinTabletStatusID], [cts].[CheckinTabletID], [cts].[TimestampUtc] FROM [CheckinTabletStatus] AS [cts] WHERE @_outer_Id = [cts].[CheckinTabletID] ORDER BY [cts].[TimestampUtc] DESC',N'@_outer_Id int',@_outer_Id=3

exec sp_executesql N'SELECT TOP(1) [cts].[CheckinTabletStatusID], [cts].[CheckinTabletID], [cts].[TimestampUtc] FROM [CheckinTabletStatus] AS [cts] WHERE @_outer_Id = [cts].[CheckinTabletID] ORDER BY [cts].[TimestampUtc] DESC',N'@_outer_Id int',@_outer_Id=4

exec sp_executesql N'SELECT TOP(1) [cts].[CheckinTabletStatusID], [cts].[CheckinTabletID], [cts].[TimestampUtc] FROM [CheckinTabletStatus] AS [cts] WHERE @_outer_Id = [cts].[CheckinTabletID] ORDER BY [cts].[TimestampUtc] DESC',N'@_outer_Id int',@_outer_Id=5

是的,这是一次调用首先获取所有实体(CheckinTablets),然后每行调用以获取每个实体的状态...

因此,在一次调用中,ToList()Entity Framework正在n+1调用数据库。这是非常不受欢迎的,有没有办法禁用此行为或解决方法?

编辑1:

.Include()没有帮助这个问题......它仍然会产生n + 1个DB请求。

编辑2(信用@jmdon):

没有返回对象但是简单的值只能进行一次调用!当然,如果您不想展平您的实体,或者您想要第二个表中的多个值,这实际上没有用。从来没有那么好知道!

var query2 = _context.CheckinTablets.Select(ct => new
{
    Id = ct.Id,
    DeviceName = ct.Name,
    Status = new CheckinTabletStatus
    {
        Id = ct.CheckinTabletStatuses.OrderByDescending(cts => cts.TimestampUtc).FirstOrDefault().Id,
        CheckinTabletId = ct.CheckinTabletStatuses.OrderByDescending(cts => cts.TimestampUtc).FirstOrDefault().CheckinTabletId,
    }
}).ToList();

产生一次对DB的调用:

SELECT [ct].[intCheckinTabletID] AS [Id0],
   [ct].[strName] AS [DeviceName],
(
    SELECT TOP (1) [cts].[intCheckinTabletStatusID]
    FROM [tCheckinTabletStatus] AS [cts]
    WHERE [ct].[intCheckinTabletID] = [cts].[intCheckinTabletID]
    ORDER BY [cts].[dtmTimestampUtc] DESC
) AS [Id],
(
    SELECT TOP (1) [cts0].[intCheckinTabletID]
    FROM [tCheckinTabletStatus] AS [cts0]
    WHERE [ct].[intCheckinTabletID] = [cts0].[intCheckinTabletID]
    ORDER BY [cts0].[dtmTimestampUtc] DESC
) AS [CheckinTabletId]
FROM [tCheckinTablet] AS [ct];
提问于
用户回答回答于

我注意到当你尝试返回嵌套对象时它会这样做。

您可以尝试在投影中展平Status对象,例如。就像是:

var query2 = context.CheckinTablets.Select(ct => new
        {
            Id = ct.Id,
            DeviceName = ct.Name,
            StatusName = ct.CheckinTabletStatuses
                .OrderByDescending(cts => cts.TimestampUtc).FirstOrDefault().Name
        }).ToList();
用户回答回答于

我在.Net Conf 2018期间向Diego Vega和Smit Patel提出了这个问题......这是他们的回答(转述)。

EF Core不仅适用于关系数据库...如果某些内容无法转换为SQL,客户也不希望看到异常......“如果它需要多个查询,那很好”...默认情况下,每个枚举有多个查询已启用。如果发生这种情况,会有一个警告系统会输出警告。他们正考虑添加一种方法,如果执行多次往返,将警告升级为异常。他们正在根据数据结构对几个(固定大小)查询进行优化(n + 1)查询。

通过将此内容添加到OnConfiguring方法,可以强制EF Core在查询部分查询客户端时抛出异常。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFQuerying;Trusted_Connection=True;")
        .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}

更多信息:https//docs.microsoft.com/en-us/ef/core/querying/client-eval

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励