[英]query multi-level entity with filter at the lowest level
So I have 3 entity classes: 所以我有3个实体类:
public partial class Event
{
public Event()
{
Recurrences = new HashSet<Recurrence>();
}
public int Id { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public partial class Recurrence
{
public Recurrence()
{
AspNetUsers = new HashSet<AspNetUser>();
}
public int Id { get; set; }
public int EventId { get; set; }
public ICollection<AspNetUser> AspNetUsers { get; set; }
}
public partial class AspNetUser
{
public AspNetUser()
{
Recurrences = new HashSet<Recurrence>();
}
public string Id { get; set; }
public string UserName { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
I would like to get the event given the aspnetuser.id using line to entity. 我想使用实体行获得给定aspnetuser.id的事件。 so far this is what I have but it's returning an error: 到目前为止,这就是我所拥有的,但是它返回一个错误:
// GET: api/Events?userId={userId}
public IQueryable<Event> GetEvents(string userId)
{
return db.Events
.Include(e => e.Recurrences
.Select(u => u.AspNetUsers.Where(i => i.Id == userId)));
}
When I exclude the where clause it works fine. 当我排除where子句时,它可以正常工作。 Please help. 请帮忙。 Thanks in advance! 提前致谢!
I don't think Include() means what you think it means. 我认为Include()并不意味着您认为的含义。 ( https://msdn.microsoft.com/en-us/library/bb738708%28v=vs.110%29.aspx ) What it does is tell the db set to be sure to bring in relationships for that object. ( https://msdn.microsoft.com/zh-cn/library/bb738708%28v=vs.110%29.aspx )它的作用是告诉数据库集确保引入该对象的关系。 By default (last I checked), the db context will auto pull in all relationships, so this isn't necessary. 默认情况下(我最后检查过),数据库上下文将自动拉入所有关系,因此这不是必需的。 However, if you've turned off the lazy-loading ( http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext.aspx ) then you'll need to .Include() all the relationships you want to have in the query. 但是,如果您关闭了延迟加载( http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext.aspx ),则需要.Include()所有关系您想要包含在查询中。
This should solve your problem. 这应该可以解决您的问题。 I don't guarantee the SQL generated won't be silly, though. 但是,我不保证生成的SQL不会很傻。
If you have lazy-loading turned on: 如果您启用了延迟加载:
db.Events.Include("Recurrences").Include("Recurrences.AspNetUsers")
.Where(e => e.Recurrences
.Any(r => r.AspNetUsers
.Any(u => u.Id ==userId)));
If you have lazy-loading turned off: 如果您关闭了延迟加载:
db.Events
.Where(e => e.Recurrences
.Any(r => r.AspNetUsers
.Any(u => u.Id ==userId)));
Also, if you have trouble seeing errors, you can .ToList() the query before returning so that it fails in your code and not deep inside the Web API stack. 另外,如果您看不到错误,可以在返回之前使用.ToList()查询,这样它就不会在您的代码中失败,也不会在Web API堆栈的深处出现。 Personally, I like to do this so that I can try/catch the query and handle it properly. 就个人而言,我喜欢这样做,以便可以尝试/捕获查询并正确处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.