2015-08-14 32 views
-1

我想加入基於ID列兩個表上Table2是在IDTable1Ef6點符號;與條件colums加入喜歡,不等於

me.dbSet.Join(me.context.Table2, p => p.ID, e => e.ID, 
(p, e) => new { p, e }).Where(z => z.e.ID== uid) 

的SQL輸出:

SELECT 
    1 AS [C1] 
    FROM [NG].[T1] AS [Extent1] 
    INNER JOIN [NG].[T2] AS [Extent2] ON [Extent1].[ID] = [Extent2].[ID] 
    WHERE [Extent2].[ID] = 'f520f7b3-215d-4dfe-9787-1eb6864fb335' 

我試圖用linq寫的sql:

SELECT 
    1 AS [C1] 
    FROM [NG].[T1] AS [Extent1] 
    INNER JOIN [NG].[T2] AS [Extent2] ON [Extent1].[ID] Like [Extent2].[ID] + '%' 
    WHERE [Extent2].[ID] = 'f520f7b3-215d-4dfe-9787-1eb6864fb335' 

回答

2

您可以與where子句中交叉聯接和StartsWith做到這一點:

var data = from t1 in Table1 
      from t2 in Table2 
      where t1.Id.StartsWith(t2.Id) 
      && t2.Id == uid 
      select new { t1, t2 }; 

它不會給予同樣的SQL,只要你想,但輸出是一樣的。只有

未經檢驗的,但使用lambda擴展方法,這應該工作:

var data = me.dbSet 
    .Join(
     me.context.Table2, 
     p => true, 
     e => true, 
     (p, e) => new { p, e }) 
    .Where(z => z.e.ID == uid && z.p.Id.StartsWith(z.e.Id)); 

另一個潛在的選擇,如果你知道ID的長度是不變的(它看起來像一個GUID,所以你也許可以依靠它長爲36個字符:

var data = me.dbSet 
    .Join(
     me.context.Table2, 
     p => p.Id.Substring(0, 36), 
     e => e.Id, 
     (p, e) => new { p, e }) 
    .Where(z => z.e.ID == uid); 
+0

是更多鈔票來用點表示寫這 – semirturgay

+0

檢查編輯,未經測試,但應該工作 – DavidG

+0

首先爲您解答所有thaks的它的工作原理,但它是在很慢?。與'table1.id +'%''加入table1.id相比因爲它加入了'on 1 = 1'表,然後過濾記錄。我正在用一個擁有超過100萬條記錄的大數據集來測試它。 – semirturgay