c# – EF连接5个大表 – Include()方法优化
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – EF连接5个大表 – Include()方法优化,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2585字,纯文字阅读大概需要4分钟。
内容图文
![c# – EF连接5个大表 – Include()方法优化](/upload/InfoBanner/zyjiaocheng/797/2bfc9df7a67741b29b7712fce9047a35.jpg)
我有以下数据库结构(EDMX模型):
public class Company
{
public Guid Id { get; set; }
public virtual ICollection<Location> Locations { get; set; }
// ... 15 more columns
}
public class Location
{
public Guid Id { get; set; }
public virtual Company Company { get; set; }
public Guid CompanyId { get; set; }
public virtual ICollection<ReportA> ReportsA { get; set; }
public virtual ICollection<ReportB> ReportsB { get; set; }
public virtual ICollection<ReportC> ReportsC { get; set; }
// ... 15 more columns with information - name, description etc.
}
public class ReportA
{
public virtual Location Location { get; set; }
public Guid LocationId { get; set; }
// 30 more columns of type "int?"
}
public class ReportB
{
public virtual Location Location { get; set; }
public Guid LocationId { get; set; }
// 30 more columns of type "int?"
}
public class ReportC
{
public virtual Location Location { get; set; }
public Guid LocationId { get; set; }
// 30 more columns of type "int?"
}
一家公司可以拥有多个地点.每个地点都有很多来自A,B和C的报告.
ReportA,ReportB,ReportC表中的列不同.
每个报告表都有大约40 000行.
公司和位??置表有大约5000行
我需要获取所有数据并制作摘要报告.
代码是:
using (ComapnyEntities dataBaseContext = new ComapnyEntities())
{
IQueryable<Locations> query = dataBaseContext.Locations
.AsNoTracking()
.Where(location => companyIds.Contains(location.CompanyId))
.Include(location => location.Company)
.Include(location => location.ReportsA)
.Include(location => location.ReportsB)
.Include(location => location.ReportsC);
// more filtation
return query.ToList();
// assume that companyIds have all company Ids
}
在大多数情况下,我可以使用Skip()和Take()方法来提高执行速度(即.Take(10)),但在一个特殊情况下,我需要将所有位置与公司信息ReportsA,ReportsB,ReportsC一起提取.
根据Stackoverflow中的注释,Include()按行生成笛卡尔积. https://stackoverflow.com/a/22625208/6142097
// so if that is true:
4 000 * 4 000 * 40 000 * 40 000 * 40 000 = ?? (1.024e+21)
“好的部分”是页面加载(本地)需要15秒,但在生产中不一样,需要更长时间.
那么有没有办法提高查询的性能?
>我试着用Entity-framework code is slow when using Include() many times – 它慢了
>我添加了Location.CompanyId,ReportA.LocationId,ReportB.LocationId,ReportC.LocationId,LocationId的Non-Clustured index – 没有区别(我不确定索引是否正确添加)
>无法构造连接所有表的本机SQL查询,这些表可以执行不到10秒.
>我尝试用.IncludeOptimized()替换.Inlude(),但没有真正的区别.
我的机器在Windows 8.1中使用SQL Server 2014
你有什么建议?有没有办法改善我的代码?
解决方法:
I need to get all of the data and make a summary report.
您不应该“获取所有数据”来“制作摘要报告”.而是编写返回摘要的查询,而不是每一行.
内容总结
以上是互联网集市为您收集整理的c# – EF连接5个大表 – Include()方法优化全部内容,希望文章能够帮你解决c# – EF连接5个大表 – Include()方法优化所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。