EF写INNER JOIN 链接

面对多表的查询,一般都是多表连接后下面再写条件,但是有一种写法可以提升一下EF生成的语句的效率

首先先去查询每一个表,把每一个表对应的条件附加上去,注意:过滤数据最多的条件放在首先位置

  var lt = from l in l 
                                             where l.UserKind == 1
                                             select l;
                if (query.CreateDateStart!=null)
                {
                    l = l .Where(t=> t.CreateDate>= query.CreateDateStart);
                }
                if (query.CreateDateEnd != null)
                {
                    l = l .Where(t => t.CreateDate <= query.CreateDateEnd);
                }
 var ot= from o in  o
                                         select o;
                if (!string.IsNullOrWhiteSpace(query.DataSource))
                {
                    o= o.Where(t => t.DataSource == query.DataSource);
                }
                if (!string.IsNullOrWhiteSpace(query.ServiceSectID))
                {
                    o= o.Where(t => t.ServiceSectID == query.ServiceSectID);
                }
                if (!string.IsNullOrWhiteSpace(query.AccessionNumber))
                {
                    o= o.Where(t => t.AccessionNumber == query.AccessionNumber);
                }
   var vt= from v in v
                                         select v;
                if (!string.IsNullOrWhiteSpace(query.MedRecNO))
                {
                    v= v.Where(t => t.MedRecNO == query.MedRecNO);
                }

以上述三张表为例,

分别取放入对应的条件,然后组合起来,写inner join

  //查询结果联表,做inner查询
                var querySql = from o in ot
                               join v in vt
                               on o.VisitUID equals v.VisitUID
                               join l in lt
                               on o.ObservationUID equals l.BusinessUID
                               select new AccessToPatientsInfo
                               {
                                   Name=p.Name,
                                   TypeCode=l.TypeCode,
                                   MedRecNO=v.MedRecNO,
                                   DataSource=o.DataSource,
                                   ServiceSectID=o.ServiceSectID,
                                   AccessionNumber=o.AccessionNumber,
                                   ServiceText=o.ServiceText,
                                   CreateDate=l.CreateDate
                               };

 

posted @ 2017-08-18 10:47  洛晨随风  阅读(1386)  评论(0编辑  收藏  举报