2015-05-14 53 views
3

Im獲取像這樣的錯誤:指定的LINQ表達式包含對與不同上下文關聯的查詢的引用。(Linq/Lambda)使用2個DBContext連接2個或多個表

var employee = new ApplicationDbContext().Employee; 
var otherTable = new OtherDbContext().OtherTable; 

var returnValue = (from e in employee 
         join o in otherTable on e.Id equals o.Id 
         select new 
         { 
          e.Name, 
          e.Address, 
          o.Others 
         }); 

任何解決方案/ s? 謝謝!

+0

我不知道,你可以在兩個上下文加盟。 EF必須以某種方式將其轉換爲SQL查詢 – garryp

+3

不可能同時查詢兩個上下文,請參閱此問題/答案:http://stackoverflow.com/questions/4278993/is-it-possible-to-perform-joins- across-different-databases-using-linq – Terence

+0

Employee或OtherTable中是否有大量數據? –

回答

2

您應該一般實例化您的DBContext並且不要指定表/模型。 例子:

private ApplicationDBContext db = new ApplicationDbContext(); 

然後選擇如果你仍然要使用LINQ或原始的SQL。我相信你更熟悉SQL,因爲你提到了連接表,所以爲什麼不使用它呢? Here's a tutorial on how to use Raw SQL.

If you still insist in using LINQ and involve join, here's a good reference for it.

+0

項目中的所有查詢都使用linq或lambda,如果我在這個特定查詢中使用原始sql,它將是unform。 謝謝! – janmvtrinidad

+0

如果我們在[SP](https://msdn.microsoft.com/en-us/data/gg699321.aspx)上創建並創建[鏈接的服務器](http:// forums),它會更好。 asp.net/t/1254974.aspx?How+to+join+tables+from+different+databases+in+SQL+select+statement+)改爲調用'.ToList()'來引起查詢。所以我會接受這個答案。 – janmvtrinidad

0
List<Employee> empList = new ApplicationDbContext().Employee.ToList(); 
List<OtherTable> othrList= new OtherDbContext().OtherTable.ToList(); 

var returnValue = (from e in empList 
         join o in othrList on e.Id equals o.Id 
         select new 
         { 
          e.Name, 
          e.Address, 
          o.Others 
         }); 

試試這個它會工作.....

+0

感謝您的迴應! .ToList()查詢所有記錄,因此查詢它可能會很緊張。 你覺得呢? 其他解決方案? – janmvtrinidad