2014-04-21 70 views
0

我想從2個不同的SQL Server(實體)使用LINQ連接3個表。Linq加入兩個實體和3個表

Error: The specified Linq expression contains references to queries that are associated with different contexts

var query = from a in EntityA.TableA 
      join p in EntityA.TableB 
      on a.PersonID equals p.PersonID 
      join m in EntityB.TableC 
      on Convert.ToInt32(a.SourceID) equals m.ID 
      where p.someID == "100000527" 
      select m.ID; 

請幫我解決這個問題。

答:

 var query = from a in EntityA.TableA 
     join p in EntityA.TableB 
     on a.PersonID equals p.PersonID 
     where p.someID == "100000527" 
     select a.ID; 

    IQueryable<int> ID = null; 

    foreach (var item in query) 
    { 
     int sourceID= Convert.ToInt32(item); 
     ID = (from m in EntityB.TableC 
       where m.ID == sourceID 
       select m.ID).Distinct(); 
    } 

    return ID; 

這是正確的做法?

+0

我看過那個鏈接。但我想我的情況有點不同,因爲我沒有得到System.NotSupportedException。我以爲我是像http://stackoverflow.com/questions/7332920/the-specified-linq-expression-contains-references-to-queries-that-are-相關 – Uba

+0

也Convert.ToInt32(a.SourceID)將無論如何不工作 –

+0

謝謝。我現在修改它。 – Uba

回答

0

一次只能在一個數據庫上將Linq寫入SQL查詢。

如果要將數據連接在一起,則必須分別編寫兩個查詢,從中創建匿名類型對象,然後使用普通的舊Linq對象將它們連接在一起。

+0

我嘗試了以下鏈接,http://stackoverflow.com/questions/7332920/the-specified-linq-expression-contains-references-to-queries-that-are-associated。但是,仍然沒有運氣。 :( – Uba