4

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

Class Favorites
Guid UserId
Guid ObjectId

Class Objects
Guid Id
String Name

使用实体框架,我想选择所有被用户标记为收藏的对象。

所以我尝试了这样的事情

context.Objects.Where(
   x => x.Id == 
   context.Favorite.Where(f => f.UserId == UserId)
   .Select(f => f.ObjectId).Any()
);

但我不明白。我也尝试过相交,但我最了解的是同一类型。一个用户可以拥有多个收藏对象

4

5 回答 5

6

你可以使用连接子句:

context.Favorite
  .Where(f => f.UserId == UserId)
  .Join(context.Objects, t => t.ObjectId, u => u.Id, (t, u) => t);
于 2012-12-05T19:46:15.247 回答
4

我会加入,我的 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;
于 2012-12-05T19:49:35.997 回答
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
于 2012-12-05T19:48:32.940 回答
0

使用 FirstOrDefault() 而不是 Any()

于 2012-12-05T19:44:41.720 回答
0

您的收藏夹类需要一个将其链接回对象的属性,而不是双 where 子句,您可以使用 Include

课程

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

Class Objects
    Guid Id
    String Name

林克

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

然后您的收藏夹对象将在其下有一个对象集合。

于 2012-12-05T19:53:54.360 回答