Entity Framework 6 中急切加载时的多个数据库查询

Multiple DB queries when Eager Loading in Entity Framework 6

我的问题是,每次加载此视图时,我的应用程序都会向数据库发送 249 个相同的查询。本来我用的是懒加载,查询次数翻倍

上面的249数字表示本次查询的行数returns。

我的理解是 .Include 创建一个应该消除这种行为的连接?

谁能告诉我如何消除这种重复查询?

干杯!

以下代码为伪代码,不可编译

控制器:

 var apples = _unitOfWork.Context.Apples
    .Include(x=> x.AppleTypes)
    .OrderByDescending(x => x.Id)
    .Where(x => x.Status == (int)AppleStatusConstants.New 
          && x.IsRejected != true && x.AppleManId != null);

 return View(apples);

查看:

@model IEnumerable<Apple>

@Html.DisplayNameFor(model => model.AppleTypes.TypeSeason)
@foreach (var item in Model){
         @Html.DisplayFor(modelItem => item.AppleTypes.TypeSeason)
         }

SQL 掠影之迹:

    SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Type] AS [Type],  
[Extent2].[Id] AS [Id1], 
[Extent2].[TypeSeason] AS [TypeSeason], 

FROM  [dbo].[Apples] AS [Extent1]
LEFT OUTER JOIN [dbo].[AppleTypes] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
WHERE (0 = [Extent1].[Status]) AND ( NOT ((1 = [Extent1].[IsRejected]) AND ([Extent1].[IsRejected] IS NOT NULL))) AND ([Extent1].[OrgUnitId] IS NOT NULL)
ORDER BY [Extent1].[Id] DESC

截图一瞥

Multiple DB queries when Eager Loading in Entity Framework 6

你没有告诉它 Eager Load base 查询,只有它包含。

此代码:

var apples = _unitOfWork.Context.Apples
  .Include(x=> x.AppleTypes)
  .OrderByDescending(x => x.Id)
  .Where(x => x.Status == (int)AppleStatusConstants.New 
         && x.IsRejected != true && x.AppleManId != null);

正在创建 IQueryable< T >。简单的解决方法是在最后添加.ToList()

  .Where(x => x.Status == (int)AppleStatusConstants.New 
     && x.IsRejected != true && x.AppleManId != null)
  .ToList(); 

所以在你的代码中,这是罪魁祸首:

@foreach (var item in Model){

这会导致 EF 一次查询一个实体。

PS: 以下语句是相同的(除非你已经覆盖了 object.cshtml)

@foreach (var item in Model){
  @Html.DisplayFor(modelItem => item.AppleTypes.TypeSeason)
}

@Html.DisplayFor(m => m)

@Html.DisplayForModel()