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

  • 相关阅读:
    python class属性
    获取安卓系统日志输出
    深入理解C#中的IDisposable接口(转)
    Mac开启自带的Apache服务器
    【转】《Unity Shader入门精要》冯乐乐著 书中彩图
    AssetDatabase的方法总结
    C# 读写XML文件的方法
    tkinter模块常用参数(python3)
    Unity在Project视图里面显示文件的拓展名
    Git忽略提交规则
  • 原文地址:https://www.cnblogs.com/shanshanlaichi/p/6666093.html
Copyright © 2020-2023  润新知