Linq to SQL实现链接加条件查询

需要显示出所有的会员信息(即MemberInfo),排序要求按照会员排序表(MemberSort)中会员类型(MemberType)为0的SortNumber列进行排序。可以总结为三条:1.需要显示出所有的会员信息;2.按照会员排序表中的SortNumber列进行排序;3.只按照会员排序表中会员类型为0的会员进行排序。

  表结构及相关测试数据脚本:

{12568658288120}createtable MemberInfo
(
    MemberID
int,
    MemberName
nvarchar(50)
)
createtable MemberSort
(
    MemberId
int,
    SortNumber
int,
    MemberType
int
)
insertinto MemberInfo values (1,'A')
insertinto MemberInfo values (2,'B')
insertinto MemberInfo values (3,'C')
insertinto MemberInfo values (4,'D')
insertinto MemberInfo values (5,'E')

insertinto MemberSort values (1,5,0)
insertinto MemberSort values (2,4,0)
insertinto MemberSort values (3,3,1)

--Drop table MemberInfo
--
Drop table MemberSort

  采用传统的SQL方式查询代码:

{12568658288121}SELECT[t0].[MemberID], [t0].[MemberName]
FROM[dbo].[MemberInfo]AS[t0]
LEFTOUTERJOIN[dbo].[MemberSort]AS[t1]ON ([t1].[MemberType]=0) AND ([t0].[MemberID]=[t1].[MemberID])
ORDERBY
    (
CASE
        
WHEN[t1].[SortNumber]ISNOTNULLTHEN[t1].[SortNumber]
        
ELSE9999
    
END)

  希望在Linq to SQL中获得同样的支持。

  首次尝试失败的代码:

{12568658288122}var data =from m in db.MemberInfo
                          
join s in db.MemberSort on m.MemberID equals s.MemberID && s.MemberType ==0
                          
into x
                          
from cx in x.DefaultIfEmpty()
                           orderby cx.SortNumber.HasValue ? cx.SortNumber.Value :
9999
                          
select m;

  经过修正代码如下:

{12568658288123}var data =from m in db.MemberInfo
                          
join s in db.MemberSort on m.MemberID equals s.MemberID
                          
into x
                          
from cx in x.Where(d => d.MemberType ==0).DefaultIfEmpty()
                           orderby cx.SortNumber.HasValue ? cx.SortNumber.Value :
9999
                          
select m;

  关键语句即from cx in x.Where(d=>d.MemberType==0).DefaultEmpty(); 即为返回连接组合当中MemberType==0或不存在MemberType值的数据集合。

  

posted @ 2012-02-01 15:10  黎明&岁月  阅读(331)  评论(0编辑  收藏  举报