我有这个匿名类型,我通过库调用形式实体框架构建,但我得到这个错误:The specified LINQ expression contains references to queries that are associated with different contexts.
下面的代码只从一个数据库拉,所以我不明白为什么这是提出。如何在不使用LINQ to SQL和Entity Framework过度调用数据库的情况下优化此查询?
// 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();
当我拨打以上在结束了ToList()方法(以电话砍倒在DB直到结束),我得到上述mentiond关于多个上下文的错误。他们都来自同一个单一的数据库,只是不同的表格,为什么这仍然被抛出,我怎么才能修复它,以便只打一个电话到数据库?
编辑:
Read方法:
public IQueryable<T> Read<T>() where T : EntityObject, new()
{
var objectSet = Context.CreateObjectSet<T>();
objectSet.MergeOption = MergeOption.PreserveChanges;
return objectSet;
}
显示你的'Read()'方法 – haim770
@ haim770好的,完成了。 –
所以问题不在于你试图调用不同的数据库。这就是你试图在一次调用中一起使用不同的'Context'实例。 – MarcinJuraszek