Entity Framework Many to Many query

↘锁芯ラ 提交于 2019-12-07 13:24:06

问题


I want to write a simple query, but there are some problems. I have 2 tables M to N:

Users -> Events.

I want to get all users of a specific event (get this event by eventId).

public IQueryable<User> GetUsersByEventId(int eventId)
{
    IQueryable<User> query = this.Context.Users.AsQueryable();

    return query.Where(x => x.Events.SingleOrDefault(e => e.EventId == eventId)); ??
}

Something is missing and I dont know what, can someone help me? Thanks a lot !


回答1:


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;



回答2:


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
}


来源:https://stackoverflow.com/questions/18419497/entity-framework-many-to-many-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!