EntityFramework 使用Linq處理內連接(inner join)、外鏈接(left/right outer join)、多表查詢


場景:在實際的項目中使用EntityFramework都會遇到使用Ef處理連接查詢的問題,這里做一些小例子如何通過Linq語法處理內連接(inner join)、外連接(left/right outer join);

廢話不多說先看實體類:

 

 1.內連接:

Linq:

var query = from st in context.SchoolBoys
            join gl in context.SchoolGirls on st.GirlfriendId equals gl.Id
            select new
            {
                Id = st.Id,
                Name = st.Name,
                GirlfriendName = gl.Name
            };

sql:

SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Name] AS [Name], 
    [Extent2].[Name] AS [Name1]
    FROM  [dbo].[SchoolBoys] AS [Extent1]
    INNER JOIN [dbo].[SchoolGirls] AS [Extent2] ON [Extent1].[GirlfriendId] = [Extent2].[Id]

2.外連接(這里只介紹左外連接)

Linq:

var  query = from st in context.SchoolBoys
             join cl in context.Classes on st.ClassId equals cl.Id into cls
             from c in cls.DefaultIfEmpty()
             select new
             {
                 Id = st.Id,
                 Name = st.Name,
                 ClassName = c.Name
             };

sql:

SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Name] AS [Name], 
    [Extent2].[Name] AS [Name1]
    FROM  [dbo].[SchoolBoys] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Classes] AS [Extent2] ON [Extent1].[ClassId] = [Extent2].[Id]

3.多表混合

linq:

var query3 = from st in context.SchoolBoys
             join gl in context.SchoolGirls on st.GirlfriendId equals gl.Id into sgs
             from sg in sgs
             join cl in context.Classes on sg.ClassId equals cl.Id into cls
             from cla in cls.DefaultIfEmpty()
             join g in context.Grades on cla.GradeId equals g.Id into gs
             from gr in gs.DefaultIfEmpty()
             select new
             {
                  Id = st.Id,
                  Name = st.Name,
                  ClassName = cla.Name,
                  GradeName = gr.Name
             };

 

sql:

    SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Name] AS [Name], 
    [Extent3].[Name] AS [Name1], 
    [Extent4].[Name] AS [Name2]
    FROM    [dbo].[SchoolBoys] AS [Extent1]
    INNER JOIN [dbo].[SchoolGirls] AS [Extent2] ON [Extent1].[GirlfriendId] = [Extent2].[Id]
    LEFT OUTER JOIN [dbo].[Classes] AS [Extent3] ON [Extent2].[ClassId] = [Extent3].[Id]
    LEFT OUTER JOIN [dbo].[Grades] AS [Extent4] ON [Extent3].[GradeId] = [Extent4].[Id]

歡迎指正 轉載請注明出處:http://www.cnblogs.com/xinwang/p/6145837.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM