我有這個匿名類型,我通過庫調用形式實體框架構建,但我得到這個錯誤: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