EF 实现left join左联接查询
using (Test db = new Test())
{
List<table3> list = (from a in db.table1
join b in db.table2 on a.Pid equals b.Pid into c
from d in c.DefaultIfEmpty()//当记录不存在时返回一个空值
select new table3 { Id = a.Id, Name = a.Name, Name2 = d.Name2 }).ToList();
}
EF所执行的sql语句为:
SELECT
`Extent1`.`Id`,
`Extent1`.`Name`,
`Extent2`.`Name2`
FROM `table1` AS `Extent1` LEFT OUTER JOIN `table2` AS `Extent2` ON `Extent1`.`Pid` = `Extent2`.`Pid`
实体类:
public class table1
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Pid { get; set; }
}
public class table2
{
[Key]
public int Pid { get; set; }
public string Name2 { get; set; }
}
public class table3
{
public int Id { get; set; }
public string Name { get; set; }
public string Name2 { get; set; }
}