2015-09-07 77 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;