2015-08-20 21 views
0

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

顯示你的'Read()'方法 – haim770

+0

@ haim770好的,完成了。 –

+1

所以問題不在於你試圖調用不同的數據庫。這就是你試圖在一次調用中一起使用不同的'Context'實例。 – MarcinJuraszek

回答

0

的多個環境是指報告,huForm和anForm。您需要將它們移到相同的上下文中,或者使用單獨的查詢從數據庫獲取數據,然後連接並加入結果。

這些閱讀中的每一個都給你一個單獨的上下文。你需要抽象你的數據庫連接,然後繼承到每個模型。

+0

我會如何「將它們移動到相同的環境」?我試圖在絕對必要時將我的數據庫調用限制在最後。我怎樣才能建立這個查詢,因爲它來自一個數據庫? –

+0

我編輯了我的答案,並希望澄清我的意思。 –

+0

我正在考慮這個問題,問題完全在其他地方。 –

相關問題