网上查到的直接使用Join+DefaultIfEmpty的方式是错误的,实际生成SQL是两表先内联接,然后再LEFT JOIN。经过查证,参考资料,最终得到如下两种方式的左连接写法:
public void TestMethod1() { MettingEntities db = new MettingEntities(); //LINQ方式 var query = (from st in db.met_SysItemsClass join cl in db.met_Shortcut on st.ClassID equals cl.ClassID into cls from c in cls.DefaultIfEmpty() select new TestModel { ClassID = st.ClassID, ClassName = st.ClassName, AdminID = c.AdminID }).ToList(); //Lambda 方式 var list = db.met_SysItemsClass.GroupJoin(db.met_Shortcut, x => x.ClassID, y => y.ClassID, (x, y) => y.DefaultIfEmpty().Select(z => new TestModel { ClassID = x.ClassID, ClassName = x.ClassName, AdminID = z.AdminID })).SelectMany(x => x).ToList(); } } public class TestModel { public int? AdminID { get; set; } public int ClassID { get; set; } public string ClassName { get; set; } }
两种方式生成的SQL语句完全相同,如下:
SELECT [Extent1].[ClassID] AS [ClassID], [Extent1].[ClassName] AS [ClassName], [Extent2].[AdminID] AS [AdminID] FROM [dbo].[met_SysItemsClass] AS [Extent1] LEFT OUTER JOIN [dbo].[met_Shortcut] AS [Extent2] ON [Extent1].[ClassID] = [Extent2].[ClassID]