EF 左链接
两个表Table1、Table2 并表查下时,如果连接字段存在空值,直接用join 查不出数据,需用左连接
var list = from v in Table1 join x in Table2 on v.Id equals x.Table1Id into newlist from d in newlist.DefaultIfEmpty()
如果两个表庞大,可以在newlist 后面加where 过滤条件,大大的提高查询性能
不过加where过滤后,在NET5版本后,很容易就报错,使用的时候注意一下
后来发现,where加的位置不对,要加在最后
//这样写报错,无法编译 var list = from v in Table1 join x in Table2 on v.Id equals x.Table1Id into newlist where v.Id > 100 from d in newlist.DefaultIfEmpty() //正确写法 var list = from v in Table1 join x in Table2 on v.Id equals x.Table1Id into newlist from d in newlist.DefaultIfEmpty() where v.Id > 100
另外的写法:
var list = from v in Table1 join x in Table2 on v.Id equals x.Table1Id into newlist from d in newlist.Where(p=>p.Id>10).DefaultIfEmpty()
如果要用到 并表后的字段(参数 d 的字段),需要把字段都改成可空类型
var list = from v in Table1 join x in Table2 on v.Id equals x.Table1Id into newlist from d in newlist.Where(p=>p.Id>10).DefaultIfEmpty() select new { v.Id, BmTypeValue=(long?)d.BmTypeValue, TrackUserId=(int?)d.TrackUserId, AddTime=(DateTime?)d.AddTime }
后续如果要使用这些可空字段,需要判断一下是否有值,或者转换成相应的非空类型,比如 int?转换成 int