简体   繁体   中英

Converting left outer join on two queries to LINQ

I have below sql query which I want to convert into LINQ to obtain exactly same results and returned by below query

    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
         )

What I have tried so far is below LINQ statement

   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);

The problem I am facing is running the SQL query is returning 30583 records and LINQ version of it is returning all of the 30613 records

I rewrote the query to be exactly like the sql query, i believe that this is the way:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM