2016-03-24 27 views
1

我的問題是,我每次加載這個視圖時,我的應用程序都會向數據庫發送249個相同的查詢。最初我使用延遲加載,查詢的數量是兩倍。Eager在實體框架中加載時的多個數據庫查詢6

上面的249數字表示此查詢返回的行數。

我的理解是,包括創建一個連接應該消除這種行爲?

誰能告訴我如何消除這種重複的查詢?

乾杯!

下面的代碼是僞代碼,不打算編譯。

控制器:

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 

掠影截圖 enter image description here

回答

1

多個數據庫查詢時預先加載在實體框架6

你還沒有告訴它渴望裝入基地查詢,只是它包含。

此代碼:

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() 
+0

是.ToList()更昂貴的操作?其中一位高級程序員鼓勵我儘可能不要使用.ToList() –

+0

沒有好的答案。這取決於。有時候'。ToList()'是正確的解決方案,而不是。 –