在EF中实现左联接

当使用EF中的dbset进行join操作的时候如果,如果表之间没有关联关系的话,生成的sql语句是 inner join(inner join 和 left join的区别 就不在这阐述了),eg:

var user = await (from u in this.context.MUser.Where(sa => sa.Id == pid)
				  join uw in this.context.MUserWechat on u.Id equals uw.UserID 
				  select new MVUserBaseInfo
				  {
					  ID = u.Id,
					  CreateTime = u.CreateTime,
					  HeadImage = u.HeadImage,
					  Phone = u.Phone,
					  UserName = u.UserName,
					  WechatBindStatus = uwti.WechatBindStatus,
					  WechatSystem = uwti.WechatSystem,
					  WechatUser = uwti.WechatUser,
					  NickName = uwti.NickName ?? string.Empty
				  }).FirstOrDefaultAsync();

这样相当于就是将MUser和MUserWechat 进行了inner join, 如果我们希望进行左连接的话可以借助DefaultIfEmpty() 来达到当联接的表为空的时候,生成一条空的数据,从而达到左联接的效果,eg:

var user = await (from u in this.context.MUser.Where(sa => sa.Id == pid)
				  join uw in this.context.MUserWechat on u.Id equals uw.UserID into uwt
				  from uwti in uwt.DefaultIfEmpty() // 变成left join
				  select new MVUserBaseInfo
				  {
					  ID = u.Id,
					  CreateTime = u.CreateTime,
					  HeadImage = u.HeadImage,
					  Phone = u.Phone,
					  UserName = u.UserName,
					  WechatBindStatus = uwti.WechatBindStatus,
					  WechatSystem = uwti.WechatSystem,
					  WechatUser = uwti.WechatUser,
					  NickName = uwti.NickName ?? string.Empty
				  }).FirstOrDefaultAsync();
posted @ 2019-01-24 18:09  Pen丶  阅读(373)  评论(0编辑  收藏  举报