关于SQL连接 加条件查询的LINQ表达式写法
为了提高开发效率,公司的的开发大量采用LINQ To SQL进行开发
在这里把项目中遇上的问题和大家分享一下。(即LINQ to sql 连接加条件查询的问题)
问题描述:
表结构以及相关测试数据脚本如下
create table MemberInfo
(
MemberID int,
MemberName nvarchar(50)
)
create table MemberSort
(
MemberId int,
SortNumber int,
MemberType int
)
insert into MemberInfo values (1,'A')
insert into MemberInfo values (2,'B')
insert into MemberInfo values (3,'C')
insert into MemberInfo values (4,'D')
insert into MemberInfo values (5,'E')
insert into MemberSort values (1,5,0)
insert into MemberSort values (2,4,0)
insert into MemberSort values (3,3,1)
--Drop table MemberInfo
--Drop table MemberSort
(
MemberID int,
MemberName nvarchar(50)
)
create table MemberSort
(
MemberId int,
SortNumber int,
MemberType int
)
insert into MemberInfo values (1,'A')
insert into MemberInfo values (2,'B')
insert into MemberInfo values (3,'C')
insert into MemberInfo values (4,'D')
insert into MemberInfo values (5,'E')
insert into MemberSort values (1,5,0)
insert into MemberSort values (2,4,0)
insert into MemberSort values (3,3,1)
--Drop table MemberInfo
--Drop table MemberSort
现在有这样一个需求,就是需要显示出所有的会员信息(即MemberInfo)的信息,但排序需按照会员排序表(MemberSort)中会员类型(MemberType)为0的SortNumber列进行排序。
听起来有点绕哈,分解一下
1.需要显示出所有的会员信息;
2.按照会员排序表中的SortNumber列进行排序;
3.只按照会员排序表中会员类型为0的会员进行排序;
内容清楚了,采用传统SQL方式查询,实现代码为
SELECT [t0].[MemberID], [t0].[MemberName]
FROM [dbo].[MemberInfo] AS [t0]
LEFT OUTER JOIN [dbo].[MemberSort] AS [t1] ON ([t1].[MemberType] =0) AND ([t0].[MemberID] = [t1].[MemberID])
ORDER BY
(CASE
WHEN [t1].[SortNumber] IS NOT NULL THEN [t1].[SortNumber]
ELSE 9999
END)
FROM [dbo].[MemberInfo] AS [t0]
LEFT OUTER JOIN [dbo].[MemberSort] AS [t1] ON ([t1].[MemberType] =0) AND ([t0].[MemberID] = [t1].[MemberID])
ORDER BY
(CASE
WHEN [t1].[SortNumber] IS NOT NULL THEN [t1].[SortNumber]
ELSE 9999
END)
我们也希望在LINQ TO sql当中获取同样的支持
即这样表达
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;
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;
但很不幸报错了。哎难道MS又开我们的玩笑,当时为了项目进度,有同事把其实现方式先换成了SQL方式实现。
后来几经周折,终于找到了答案
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;
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值的数据集合。
问题解决了,希望可以让朋友们少走弯路,遇到类似的问题可以很容易得到解决