如何在EF中實現left join(左聯接)查詢

在EF中,當在dbset使用join關聯多表查詢時,鏈接查詢的表若是沒有創建相應的外鍵關係時,EF生成的SQL語句是inner join(內聯),對於inner join,有所瞭解的同窗都知道,不少時候這並非咱們的本意,實例以下:spa

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(左聯接)查詢!code

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的效果。blog

相關文章
相關標籤/搜索