使用Where和SelectMany

Mig*_*ura 0 c# linq entity-framework

我有以下实体:

public class Position
{
    public Int32 Id { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
}

public class Role
{
    public Int32 PositionId { get; set; }
    public Int32 UserId { get; set; }
    public virtual Position Position { get; set; }
    public virtual User User { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我需要把所有Positions具有RoleUserId = userId.

我使用以下方法使其工作:

positions = positions
  .Where(x => x.Roles.Select(y => y.UserId).Contains(userId));
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做SelectMany?好点吗?

请注意,我需要返回位置......这是我使用时的问题SelectMany.

Ale*_*oma 6

你不需要Select或者SelectMany,简单的地方应该工作.

你需要using System.Linq这个工作

  List<Position>  positions = positions
      .Where(x => x.Roles.Any(y => y.UserId == userId)).ToList();
Run Code Online (Sandbox Code Playgroud)