首页 > 数据库 >EF使用LINQ和Lamda实现SQL查询的内连接(INNER JOIN)和左连接(LEFT JOIN)

EF使用LINQ和Lamda实现SQL查询的内连接(INNER JOIN)和左连接(LEFT JOIN)

时间:2022-12-05 10:35:47浏览次数:78  
标签:UserName Lamda JOIN log UserId dbContext SystemUserInfo OperateLogInfo 连接

摘自:https://www.freesion.com/article/7263358177/

 背景介绍:
1.OperateLogInfo:日志表
2.SystemUserInfo:用户表
需求:查询日志表,要根据日志表的创建人id查询出创建人姓名(日志表连接用户表)

 内连接

1、sql方式实现

select log.Id,log.UserId,user.UserName 
from OperateLogInfo log,SystemUserInfo user
where log.UserId = user.UserId

2、linq

var dataListByInnerJoinLinq = from o in dbContext.OperateLogInfo join u in dbContext.SystemUserInfo on o.UserId equals u.UserId
                               select new
                               {
                                   LogId = o.Id,
                                   CreateUserId = o.UserId,
                                   CreateUserName = u.UserName
                               };  

3、linq  lamda

var dataListByInnerJoinLamda = dbContext.OperateLogInfo.Join(dbContext.SystemUserInfo, r => r.UserId, r => r.UserId,
                      (o, u) => new
                      {
                          LogId = o.Id,
                          CreateUserId = o.UserId,
                          CreateUserName = u.UserName
                      }).ToList();

  

左连接

 1、sql方式实现

select log.Id,log.UserId,user.UserName 
from OperateLogInfo log left join SystemUserInfo user on log.UserId = user.UserId

 2、linq

var dataListByLeftJoinLinq = from o in dbContext.OperateLogInfo join u in dbContext.SystemUserInfo on o.UserId equals u.UserId into ouJoin
                                             from ou in ouJoin.DefaultIfEmpty()
                                             select new
                                             {
                                                 LogId = o.Id,
                                                 CreateUserId = o.UserId ,
                                                 CreateUserName = ou.UserName
                                             };

 

3、linq  lamda

var dataListByLeftJoinLamda = dbContext.OperateLogInfo.GroupJoin(dbContext.SystemUserInfo, r => r.UserId, r => r.UserId,
                        (o, uList) => new { Log = o, Users = uList })
                .SelectMany(r => r.Users.DefaultIfEmpty(),(ou, u) => new { Log = ou.Log, User = u })
                .Select(r => new   {   LogId = r.Log.Id,   CreateUserId = r.Log.UserId,   CreateUserName = r.User.UserName   }).ToList();

 

标签:UserName,Lamda,JOIN,log,UserId,dbContext,SystemUserInfo,OperateLogInfo,连接
From: https://www.cnblogs.com/Swaggy-yyq/p/16951561.html

相关文章