2

T-SQL:

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无法推断类型参数的关键字。

有任何想法吗?

4

3 回答 3

1

您加入的问题是您暗示LocationId( t.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 抱怨将 apostLocations作为参数传递,您可以尝试

// 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();
于 2012-04-12T03:17:38.287 回答
1

我认为您不能将 SQL 表与内存中的对象列表连接起来,即使这些对象最初来自数据库。

将内存中的对象列表转换为 id 列表(整数),并在连接或包含/子选择中使用它。EF 可以在生成 SQL 时将 id 列表转换为参数。

于 2012-04-11T06:36:50.223 回答
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(); 
于 2012-04-11T05:47:44.237 回答