EF的左连接查询
在EF中,当在dbset使用join关联多表查询时,连接查询的表如果没有建立相应的外键关系时,EF生成的SQL语句是inner join(内联),对于inner join,有所了解的同学都知道,很多时候这并不是我们的本意,实例如下:
var list = from o in context.CTMS_OD_ORDERS
join d in context.CTMS_SUP_DOCTOR
on o.OWNERDOCID equals d.USERID
join e in context.CTMS_OD_ORDERSEVALUATION
on o.ORDERID equals e.ORDERID
select o;`
EF生成了内连接(inner join)查询,当两个表的任一表的数据不匹配时,查询结果就为空!实际上left join(左联接)才是我们想要的,那么怎么样才能生成left join查询呢?其实只要我们如下改造,EF就能为我们生成left join(左联接)查询!
data = from o in context.CTMS_OD_ORDERS
join d in context.CTMS_SUP_DOCTOR
on o.OWNERDOCID equals d.USERID into dc
from dci in dc.DefaultIfEmpty()
join e in context.CTMS_OD_ORDERSEVALUATION
on o.ORDERID equals e.ORDERID into ec
from eci in ec.DefaultIfEmpty()
where o.USERID == userID && (string.IsNullOrEmpty(type) || o.PRODUCTNAME.Contains(type))
select new ODOrders
{
BalanceStatus = o.BALANCESTATUS,
ChannelOrderID = o.CHANNELORDERID,
ChannelType = o.CHANNELTYPE,
CreateDateTime = o.CREATEDATETIME,
CreateUserID = o.CREATEUSERID,
CreateUserName = o.CREATEUSERNAME,
DocName = dci.DOCNAME,
EvalutionStatus = string.IsNullOrEmpty(eci.ORDERID) ? "0" : "1",
PayTime = o.PAYTIME,
ProductCode = o.PRODUCTCODE,
ProductName = o.PRODUCTNAME,
ProductInstanceId = o.PRODUCTINSTANCEID,
ProductID = o.PRODUCTID,
OrderID = o.ORDERID,
OrderCode = o.ORDERCODE,
OrderStatus = o.ORDERSTATUS,
OrderType=o.ORDERTYPE,
TotalFee = o.TOTALFEE,
UserID=o.USERID,
UserName=o.USERNAME
};
对比上下两种写法,可以看到在on表的后面我们加上了into xx
,还有不要忘记,还需加上from xxx in xx.DefaultIfEmpty()
,重要的就是最后的xx.DefaultIfEmpty()
,它的作用是当连接的表为空时也会有一条空的数据,达到了left join的效果。