实体框架多对多查询 [英] Entity Framework Many to Many query
问题描述
我想写一个简单的查询,但是有一些问题. 我有2张桌子M到N:
I want to write a simple query, but there are some problems. I have 2 tables M to N:
用户->事件.
我想获取特定事件的所有用户(通过eventId获取此事件).
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 !
推荐答案
如果我对您的理解正确(添加模型会有所帮助),我认为您想要Any
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));
}
这将返回所有事件与给定ID匹配的所有用户.
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; }
}
因此,您将通过ID获取事件并访问它的用户集合.
So then, you'd get the Event by id and access it's user collection.
var evt = repo.GetEventById(id);
var users = evt.Users;
这篇关于实体框架多对多查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!