zoukankan      html  css  js  c++  java
  • Lambda方式左连接有Linq方式左连接

    网上查到的直接使用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]
  • 相关阅读:
    fileupload直接获得
    ajax分页
    jquery.cookie.js
    DataTable分页
    C#字串与Unicode互相转换方法
    Linq测试
    滚动条加载数据
    创建.PDF文件【1】
    小问题【6】
    小问题【4】
  • 原文地址:https://www.cnblogs.com/superfeeling/p/7530549.html
Copyright © 2011-2022 走看看