【发布时间】:2014-09-09 00:06:08
【问题描述】:
我正在使用 EF 6.1.1,我正在尝试使用下面的 LINQ 查询来拉回数据。我可以用不到 30 行手动编写这个查询,但实体框架正在做这件事。看看下面的 SQL,我是不是遗漏了什么?
LINQ
_UserRepository
.Query()
.Include(a => a.PaymentSchedules)
.Include(a => a.Profile.ProfileImages)
.Include(a => a.Profile.ProfileImages.Select(c => c.Image.HomePageImage)) //<<< this causes 100+ joins
.Include(a => a.Profile.ProfileImages.Select(i => i.Image.HoverOverImage)) //<<< this causes 100+ joins
.AsQueryable()
.Where(a => a.PaymentSchedules.Any(p => p.Active == true && p.DatePaid > eighthOfMonth))
.Where(a => a.Profile.ProfileImages.Any(prof => prof.CurrentImage == true))
.Select(a => a.Profile)
.OrderBy(a => a.Id) //require for using skip
.Skip(skipInt)
.Take(takeInt)
.ToList();
SQL
**Stackoverflow 甚至不允许我发布 SQL,因为它超过 100K 个字符并且包含超过 200 个左连接!!
请帮忙。
** 已编辑:复制粘贴失败。
【问题讨论】:
-
属性
[user].Profile.ProfileImages和[user].ProfileImages是否都引用相同的ProfileImage数据类型? -
另外,
[user]模型上的ProfileImages导航属性是否必要? -
我遇到了复制粘贴失败,我更新了代码。 ProfileImages 的用户没有导航属性。当我运行没有最后两个包含的查询时,它可能会运行 30 行 SQL。当我将它们添加回来时,我得到了数千行和数百个连接。 -A
-
如果您删除第一个 ProfileImages。让这个: .Include(a => a.Profile.ProfileImages) // 删除这个 .Include(a => a.Profile.ProfileImages.Select(c => c.Image.HomePageImage)) // a.Profile.ProfileImages.Select(i => i.Image.HoverOverImage)) //
-
我个人只会使用准备一些较小的查询来填充上下文,而不是尝试做一个包含许多包含的大型查询。 IE 一个主要查询来加载配置文件,然后单独查询来获取他们的付款时间表,另一个查询来加载他们的图像。如果正确声明导航属性,上下文将识别图形
标签: c# sql linq entity-framework timeout