Asp.net mvc 在Entity Framework 6中急切加载时的多个DB查询
我的问题是,每次加载此视图时,我的应用程序都会向数据库发送249个相同的查询。最初我使用的是延迟加载,查询的数量是原来的两倍 上面的249数字表示此查询返回的行数 我的理解是.Include创建一个应该消除这种行为的联接 有人能告诉我如何消除这种重复的查询吗 干杯 下面的代码是伪代码,不用于编译 控制器:Asp.net mvc 在Entity Framework 6中急切加载时的多个DB查询,asp.net-mvc,entity-framework,eager-loading,Asp.net Mvc,Entity Framework,Eager Loading,我的问题是,每次加载此视图时,我的应用程序都会向数据库发送249个相同的查询。最初我使用的是延迟加载,查询的数量是原来的两倍 上面的249数字表示此查询返回的行数 我的理解是.Include创建一个应该消除这种行为的联接 有人能告诉我如何消除这种重复的查询吗 干杯 下面的代码是伪代码,不用于编译 控制器: var apples = _unitOfWork.Context.Apples .Include(x=> x.AppleTypes) .OrderByDescendin
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)
}
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
查看:
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)
}
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
一瞥截图
在Entity Framework 6中急切加载时的多个DB查询
您没有告诉它立即加载基本查询,只告诉它包含
此代码:
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
。简单的解决方案是在末尾添加.ToList()
.Where(x => x.Status == (int)AppleStatusConstants.New
&& x.IsRejected != true && x.AppleManId != null)
.ToList();
因此,在您的代码中,这是罪魁祸首:
@foreach (var item in Model){
这将导致EF一次查询一个实体
PS:以下语句是相同的(除非您重写了object.cshtml)
及
及
.ToList()是一个更昂贵的操作吗?这里的一位高级程序员鼓励我尽可能不要使用.ToList()。这不是一个好答案。这要看情况而定。有时
.ToList()
是正确的解决方案,有时则不是。