左连右连还是内连这个其实你不需要关心。只需要根据实体的映射关系写查询,框架会自动帮你生成的。 至于linq查询语法与扩展方法的效率,应该是一样的,比如:
var users=(from u in db.Users where u.UserRoleId==1 select u) .ToList();
var users2=db.Users.Where(u=>u.UserRoleId==1).ToList();
这两句查询实际上是等效的。
inner join:
var =from x in db.T1
join y in db.T2
on x.yId equals y.Id
select x;
left join:
var =from x in db.T1
join y in db.T2
on x.yId equals y.Id into temp
from y in temp.DefalutIfEmpty()
select new{x.Id,Name=y==null "":y.Name};
right join 原理同 left join
至于效率,lamda表达式同标准表达式
LINQ TO EF 用 from x in temp.DefalutIfEmpty() 不是百分百会执行左连接的
主要要看 关系的配置 以及数据库那边 是否为空 外键
linq中怎么实现多条件关联的左连接???
sql语句:
SELECT * FROM T_COURSE a left join T_USER_COURSE_RECORD tucr ON a.COURSE_ID=tucr.COURSE_ID
and tucr.[USER_ID]=@userId
userId是传入的参数
var data = from c in db.T_COURSE join u in db.T_USER_COURSE_RECORD on new { COURSE_ID=(long?)c.COURSE_ID, USER_ID=(long?)userId } equals new { COURSE_ID=u.COURSE_ID,USER_ID=u.USER_ID } into x from cx in x.DefaultIfEmpty() select new { c.COURSE_NAME, cx.COURSE_ID, USER_COURSE_ID = cx == null ? 0:cx.USER_COURSE_ID, cx.USER_ID, SCORE = (cx == null | cx.SCORE == -1) ? "未完成" : cx.SCORE.ToString(), }; return data;