[英]How to optimize this query without making excessive calls to db using LINQ to SQL and Entity Framework?
I have this anonymous type that I'm building through repository calls form Entity Framework but am getting this error: The specified LINQ expression contains references to queries that are associated with different contexts.
我有这种匿名类型,我正在通过Entity Framework的存储库调用构建的,但遇到了此错误: The specified LINQ expression contains references to queries that are associated with different contexts.
The code below only pulls from one database so I do not understand why this is being raised. 下面的代码仅从一个数据库中提取,因此我不明白为什么要提出这个问题。
// listOfReportIDs is a list of ints
var reports = BusinessLogic.Repository.Read<Report>().Where(r => listOfReportIDs.Contains(r.ReportID));
var huForm = BusinessLogic.Repository.Read<HumanCase>().Where(h => listOfReportIDs.Contains(h.ReportID));
var anForm = BusinessLogic.Repository.Read<AnimalCase>().Where(a => listOfReportIDs.Contains(a.ReportID));
var reportSummaryData = from r in reports
from h in huForm.Where(h => h.ReportID == r.ReportID)
from a in anForm.Where(a => a.ReportID == r.ReportID)
select new
{
CDC_ReportID = r.CDCReportID,
StateReportID = r.StateReportID,
r.ReportDate,
ReportStatus = r.LookupReportStatus.LookupReportStatusName,
r.AuthorID,
h.HumanComment,
a.AnimalComment
};
var reportData = reportSummaryData.ToList();
When I call the ToList() method above at the end (in order to cut down calls to the db til the end), I get the error mentiond above about multiple contexts. 当我结束时调用上面的ToList()方法时(为了减少到结束时对数据库的调用),我收到了上面提到的有关多个上下文的错误。 They all come from the same single database, just different tables, why is this still being thrown and how can I fix it in order to only make one call to the db? 它们都来自同一个数据库,只是不同的表,为什么仍然抛出该异常,并且如何仅为了对db进行一次调用而对其进行修复?
EDIT: 编辑:
Read method: 读取方法:
public IQueryable<T> Read<T>() where T : EntityObject, new()
{
var objectSet = Context.CreateObjectSet<T>();
objectSet.MergeOption = MergeOption.PreserveChanges;
return objectSet;
}
The multiple contexts refers to reports, huForm and anForm. 多个上下文是指报表,huForm和anForm。 You need to move these to the same context, or use separate queries to get the data from the database, and join then join the results. 您需要将它们移至相同的上下文,或使用单独的查询从数据库中获取数据,然后联接然后联接结果。
Each of those reads is giving you a separate context. 每种读物都为您提供了单独的上下文。 You need to abstract your db connection and then inherit to each of the models. 您需要抽象数据库连接,然后继承到每个模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.