Entity Framework Many to Many query

百般思念 提交于 2019-12-06 03:56:44

If I understand you correctly (adding your models would help), I think you want Any

public IQueryable<User> GetUsersByEventId(int eventId)
{
      return Context.Users
                    .Where(u => u.Events.Any(e => e.EventId == eventId));
}

This should return all users who have any event matching the given id.

Note: If you set up your relationships correctly, you should be able to get this directly from the Event.

public class Event
{
    ...
    public virtual ICollection<User> Users { get; set; }
}

So then, you'd get the Event by id and access it's user collection.

var evt = repo.GetEventById(id);
var users = evt.Users;

I suggest you do that in your Event model itself. AFAIK you are using Event, User and EventUsers tables which is standard stuff for many2many.

public class Event
{
    public int Id { get; set; }
    // ...
    public virtual ICollection<EventUsers> EventUsers { get; set; } // This is table that holds EventId, UserId (many2many)
    public IQueryable<User> Users { get { return this.EventUsers.Select(x => x.User); } } // Get all users that are in this event
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!