簡體   English   中英

實體框架:如何在多個表中執行與EF和LINQ的左連接

[英]Entity Framework: How to perform left join with EF and LINQ among multiple tables

基本上我有3個表,那些是user,colors and usercolor

表格信息

User Tables has fields like -> UserID, UserName

Color Tables has fields like -> ColorID, ColorName

UserColor Tables has fields like -> UserID, ColorID

我的代碼中有相應的dbset classes

現在看看下面的查詢,其中在sql中的3個表中執行左連接,並告訴我如何使用EF和LINQ編寫相同的等效查詢。

select c.ColorID
    , c.ColorName
    , IsSelected = case when uc.ColorID is null then 0 else 1 end
from dbo.Colors c
left join dbo.UserColor uc on uc.ColorID = c.ColorID and uc.UserID = 1 --leave this in the join or it becomes an inner join
left join dbo.Users u on u.UserID = uc.UserID

您可以嘗試如下所示。

var result = from c in dbo.Colors 
             join uc in dbo.UserColor on (uc.ColorID = c.ColorID and uc.UserID = 1) into UserColor
             from q in UserColor.DefaultIfEmpty() join u in dbo.Users 
             on q.UserID equals u.UserID into Users
             from l in Users.DefaultIfEmpty()
             select new
               {
                 ColorID = c.ColorID,
                 ColorName = c.ColorName,
                 IsSelected = uc.ColorID == null ? 0 : 1
               };

您可以在LINQ to Entities中閱讀有關Left Outer Join的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM