2015-09-07 75 views
4

我有下面的SQL查詢,我想轉換成LINQ獲得完全相同的結果和下面的查詢返回轉換左外連接兩個查詢LINQ

select * 
      from (
       select distinct DocID 
       from UserViewDoc 
       where UserViewDoc.UVID in (102558)) a 
     left outer join 
      (
       select distinct UserViewDoc.DocID 
       from UserViewDoc 
        inner join UserViewHeader on UserViewDoc.UVID =  UserViewHeader.UVID 
       where UserViewDoc.UVID not in (102558) 
        and UserViewHeader.IsLock = 1) b on a.DocID = b.DocID 
     where b.DocID is null 
     ) 

我已經試過到目前爲止低於LINQ聲明

var v = (from uvd in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>() 
       where IDs.Contains(uvd.UVID) 
       select new { uvd.DocID, uvd.UVID }); 
     var c = ((from uvd in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>() 
       join uvh in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewHeader>() on uvd.UVID equals uvh.UVID 
       where !IDs.Contains(uvh.UVID) && uvh.IsLock == true 
       select new { uvd.DocID, uvd.UVID })); 
     var d = (from id in v 
       join ids in c on id.UVID equals ids.UVID into vc 
       from sub in vc.DefaultIfEmpty() 
       where sub == null 
       select id); 

我對着正在運行的SQL查詢的問題正在恢復30583條記錄和LINQ版本的它返回所有的30613條記錄

+1

這是偉大的,你告訴你自己的努力,但也還知道爲什麼它顯然不會做你試圖實現什麼?另外,通常可以使用導航屬性來解決連接問題,而不是LINQ連接。 –

+0

@GertArnold謝謝!!,對不起,我錯過了一個實際上當我運行SQL查詢它返回30583記錄,但在LINQ中運行同樣的事情返回所有的30613記錄。另外,我可以使用Navigational屬性,因爲它最終會將一百萬條記錄加載到memeory –

+0

您的SQL和LINQ語句不會執行相同的操作。這可能解釋了返回行中的差異。你的_actual_ SQL是什麼? – Corey

回答

0

我重寫查詢是完全一樣的SQL查詢,我認爲,這是這樣的:

var firstQuery = (from u in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>() 
        where IDs.Contains(u.UVID) 
        select u.DocID).Distinct(); 

var innerQuery = (from u in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>() 
         join uvh in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewHeader>() on uvh.UVID equals u.UVID 
         where IDs.Contains(u.UIVD) == false 
         && uvh.IsLock 
         select u.DocID).Distinct(); 

var resultQuery = from f in firstQuery 
        join i in innerQuery on i equals f into lout 
        from i in lout.DefaultIfEmpty() 
        where i == null 
        select f;