在 ObjectQuery 中使用 Contains
这是我的情况:
我有艺术家和事件之间的 am:n-关系。我想做的是获取一个仅包含包含特定艺术家的事件的 IQueryable。我正在为我的数据访问层使用存储库。显然以下方法不起作用:
_db.EventSet.Include("Location").Where(e => (e.Artists.Contains(artist)) && (e.StartDate > System.DateTime.Now)).OrderBy(e => e.StartDate);
由于我是实体框架的新手,我不太明白为什么,但我可以猜测。因此,如果有人能以一种非常简单的方式解释这一点,我也将不胜感激。无论如何,我提出的解决方案如下所示:
IQueryable<Event> events = _db.EventSet.Include("Location").Where(e => (e.EndDate > System.DateTime.Now));
List<Event> eventsList = new List<Event>();
foreach (var ev in events)
{
eventsList.Add(ev);
}
return (IQueryable<Event>)eventsList.AsQueryable().Where(e => e.Artists.Contains(artist)).OrderBy(e=>e.StartDate);
这根本不是一个好的解决方案,因为所有事件都被检索和处理,这是一个巨大的开销。有没有人可以告诉我更好的解决方案来解决我的问题?我还意识到我并没有真正理解 ObjectQuery 是什么以及如何将其转换为 IQueryable (如果可能的话)。
我很感激任何建议。
Here is my situation:
I've got a m:n-relation between artists and events. What I'm trying to do is to get a IQueryable containing only events that include a certain artist. I'm using a repository for my data access layer. Obviously the following approach doesn't work:
_db.EventSet.Include("Location").Where(e => (e.Artists.Contains(artist)) && (e.StartDate > System.DateTime.Now)).OrderBy(e => e.StartDate);
Since I'm new to Entity Framework I don't really understand why, but I can guess. So in case someone could explain this in a very easy way I would be grateful too. Anyway, my solution I came up with looks as follows:
IQueryable<Event> events = _db.EventSet.Include("Location").Where(e => (e.EndDate > System.DateTime.Now));
List<Event> eventsList = new List<Event>();
foreach (var ev in events)
{
eventsList.Add(ev);
}
return (IQueryable<Event>)eventsList.AsQueryable().Where(e => e.Artists.Contains(artist)).OrderBy(e=>e.StartDate);
That this is not a good solution at all, since ALL the events are retrieved and processed which is a massive overhead. Is there anybody out there who could tell me a better solution for my problem? I'm also aware of the fact that I didn't really understand what an ObjectQuery is and how to cast it to a IQueryable (if that's even possible).
I'm grateful for any suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将 Any 与“艺术家 ID”字段一起使用,此处假设名称为
艺术家ID
:You can use Any with the Artist ID field, here assuming a name of
ArtistId
: