Linq any - 如何选择

4

我有一些简单的类,看起来像这样:

Class Favorites
Guid UserId
Guid ObjectId

Class Objects
Guid Id
String Name

使用Entity Framework,我希望选择所有被用户标记为收藏的对象。
所以我尝试了以下代码:
context.Objects.Where(
   x => x.Id == 
   context.Favorite.Where(f => f.UserId == UserId)
   .Select(f => f.ObjectId).Any()
);

但我不明白。我也尝试了intersect,但据我理解它必须是相同的类型。一个用户可以有多个收藏对象。


你是否有导航属性,例如Favorite.Object? - Sergey Sirotkin
5个回答

6
您可以使用连接子句(join clause):
context.Favorite
  .Where(f => f.UserId == UserId)
  .Join(context.Objects, t => t.ObjectId, u => u.Id, (t, u) => t);

1
感谢,我们这边也加了+1。 - Jahan Zinedine

4

我会使用join,我的linq代码如下:

var matches = from o in context.Objects
join f in context.Favorite on o.Id equals f.ObjectId
where f.UserId == UserId
select o;

1
from o in context.Objects
join f in context.Favorites on o.Id equals f.ObjectId
where f.UserId == @userId
select //whatever you wants

0
你喜欢的类需要一个将其与对象连接起来的属性,并且可以使用Include来代替双重where子句。

Class Favorites
    Guid UserId
    Guid ObjectId
    [ForeignKey("Id")]
    Objects objs

Class Objects
    Guid Id
    String Name

Linq

context.Favorites.Include(objs).Where(x => x.UserID == UserID)

然后您的收藏夹对象下面会有一组对象。


0

使用FirstOrDefault()代替Any()


我更新了问题。一个用户有很多收藏夹。所以首选或默认只匹配第一个。 - Simon Edström

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接