2012-04-11 28 views
2

T-SQL:無法將T-SQL INNER JOIN到LINQ,查詢實體

declare @postlocations table (locationid int) 
insert into @postlocations 
select locationid 
from dbo.PostLocations 
where PostId = 162172 

select t.* 
from dbo.Themes t 
inner join dbo.ThemeLocations tl on t.ThemeId = tl.ThemeId 
inner join @postlocations pl on tl.LocationId = pl.locationid 

LINQ的實體,我至今:

var postLocations = e.SomePost.Locations; // pre-fetched, e.g materialized ICollection<Post> 
var themes = (from t in db.Themes 
      join q in postLocations on t.Locations.Select(l => l.LocationId) equals q.LocationId 
      select t).ToList(); 

但是,編譯器是抱怨的join關鍵字不能推斷出類型參數。

任何想法?

+0

爲什麼你的T-SQL兩個獨立查詢開始?它看起來應該是一個單一的查詢。 – 2012-04-11 06:51:19

+0

@Damien_The_Unbeliever - 因爲第一個實際上是一個內存集合。相同的源數據,但已經預取。 – RPM1984 2012-04-11 08:07:08

回答

0

編輯

這個怎麼樣

///your sql query 
select t.* from dbo.Themes t 
inner join dbo.ThemeLocations tl on t.ThemeId = tl.ThemeId 
inner join @postlocations pl on tl.LocationId = pl.locationid 

//linq query for that 
from t in teams 
join from tl in teamlocation on t.themid = tl.ThemeID 
join from pl in postlocation on tl.temeid = pl.temeid 
select t; 

組織

不知道,但你可以通過使用let關鍵字

var themes = (from t in db.Themes 
       let location = t.Locations 

      join q in postLocations on location.LocationId equals q.LocationId 
      select t).ToList(); 
1

我不嘗試一下認爲你可以n使用內存對象列表連接SQL表,即使這些對象最初來自數據庫。

將內存中的對象列表轉換爲id(整數)列表,並將其用於連接或Contains/sub-select中。在生成SQL時,EF可以將ID列表轉換爲參數。

1

加入的問題在於,您暗示的集合LocationIdt.Locations.Select(l => l.LocationId)可以等於一個LocationId。您正嘗試將包含位置集合的主題加入到單個位置。

您應該能夠通過使用Contains

var themes = (from t in db.Themes 
      join q in postLocations 
      on t.Locations.Select(l => l.LocationId).Contains(q.LocationId) 
      select t).ToList(); 

解決這一問題,或者如果EF抱怨傳遞postLocations作爲參數,你可以嘗試

// I'd materialize this but you may not have to 
var postLocationIds = postLocations.Select(p => p.LocationId).ToList(); 

var themes = db.Themes.Where(t => t.Locations.Any(l => 
       postLocationIds.Contains(l.LocationId))).ToList();