在LINQ查询中执行内部联接

时间:2016-11-29 09:13:23

标签: c# sql linq

我需要加入LINQ查询,我已经单独完成但在一个过程中努力做到了。

SQL脚本

SELECT af.submission_id, af.created_date, af.surname,af.first_name
FROM app_forms af
INNER JOIN (SELECT * FROM sync_audit_log sal WHERE sal.log_Status='EP' AND sal.lookup_id IS NULL AND id=(SELECT Max(id) FROM sync_audit_log sal2 WHERE  sal.submission_id=sal2.submission_id)) sal ON sal.submission_id=af.submission_id 
LEFT JOIN ebs_sync es ON af.submission_id=es.submission_id
WHERE es.person_code IS NULL

LINQ

 var query = (from af in _uof.Web_AppFormsRepository.GetAll()
                         select af).ToList();

 var query2 = (from sal in _uof.Web_SyncAuditLogRepository.GetAll().Where(sal => sal.LOG_STATUS.Equals("EP") && sal.LOOKUP_ID!=null )
                          select sal.ID).ToList();

 var query3 = (from sal2 in _uof.Web_SyncAuditLogRepository.GetAll()
                          select new { sal2.ID }).ToList();

2 个答案:

答案 0 :(得分:0)

首先你应该明白,当你调用ToList()时,EF会向数据库发出请求,我的意思是你现在对db做了3次独立请求而不是只有一次。只有在准备执行一个主查询时才调用ToList。

关于加入Linq has join operator just use it 您可以使用sql语法或表达式语法  see this question for examples

答案 1 :(得分:0)

IEnumerable<T> leftInnerJoin = from i in left join j in right on i.condition equals j.condition select i;

IEnumerable<T> leftOuterJoin = from i in left join j in right on i.condition equals j.condition into grp from k in grp.DefaultIfEmpty() where k == null select i;

IEnumerable<T> rightOuterJoin = from i in right join j in left on i.condition equals j.condition into grp from k in grp.DefaultIfEmpty() where k == null select i;

IEnumerable<T> groupJoin = leftOuterJoin.Union(rightOuterJoin).Union(leftInnerJoin);