2010-03-30 72 views
0

我有以下SQL查詢: -如何實現一個左外連接的實體框架

select distinct * from dbo.Profiles profiles 
left join ProfileSettings pSet on pSet.ProfileKey = profiles.ProfileKey 
left join PlatformIdentities pId on pId.ProfileKey = profiles.Profilekey 

我需要將其轉換爲LinqToEntities表達。我試過以下內容: -

from profiles in _dbContext.ProfileSet 
          let leftOuter = (from pSet in _dbContext.ProfileSettingSet 
              select new 
                 { 
                  pSet.isInternal 
                 }).FirstOrDefault() 
select new 
             { 
              profiles.ProfileKey, 
              Internal = leftOuter.isInternal, 
              profiles.FirstName, 
              profiles.LastName, 
              profiles.EmailAddress, 
              profiles.DateCreated, 
              profiles.LastLoggedIn,            
             }; 

上面的查詢工作正常,因爲我沒有考慮第三個表「PlatformIdentities」。單一的左外連接與我上面所做的一樣。我如何包含PlatformIdentities(第三張表)?我基本上想要將我在本文開頭指定的SQL查詢(這正是我所需要的)轉換爲LinqToEntities。

感謝

+0

什麼是'profiles.ProfileSettings'和'profiles.PlatformIdentities'的基數? – 2010-03-31 12:41:15

+0

這兩個表與他們的父表「Profiles」共享一對多關係。他們之間沒有任何基數。 – user206736 2010-03-31 17:04:21

+0

恩,好吧,但是你只是想抓住許多(每個問題中的LINQ)的第一個記錄?你想要哪張唱片? – 2010-03-31 18:47:47

回答

0

讓我知道,如果你要選擇不同的東西,但真正加盟低於

from p in _dbContext.ProfileSet 
       join ps in _dbContext.ProfileSettings on p.ProfileKey = ps.ProfileKey into a 
       join pi in _dbContext.PlatformIdentities on p.ProfileKey = pi.ProfileKey into b 

       select new 
       { 
        profiles.ProfileKey, 
        profiles.FirstName, 
        profiles.LastName, 
        profiles.EmailAddress, 
        profiles.DateCreated, 
        profiles.LastLoggedIn, 
        PlatformSettings = a.Select(x=>x), 
        PlatformIdentities = b.Select(y=>y) 
       } 
+0

上面的查詢不起作用,因爲外鍵列(ProfileKey)不能作爲linq中的屬性訪問到像linq到sql這樣的實體。這將在EF 4.0版中得到修復,該版本將在.NET 4.0中發佈,它將在我讀過的下個月發佈。 – user206736 2010-04-01 01:26:40

+0

您將會收到與此類似的錯誤消息: - 'DAL.EntityModels.ProfileSetting'不包含'ProfileKey'的定義,也沒有接受類型'DAL.EntityModels.ProfileSetting'類型的第一個參數的擴展方法'ProfileKey'可以被發現(添加使用指令或程序集引用) – user206736 2010-04-01 01:30:26

+0

我基於你提供的SQL的聯接,這聽起來像你已經改變了你的概念模型。 – Nix 2010-04-01 12:29:34