在 ObjectQuery 中使用 Contains

发布于 2024-10-02 13:41:35 字数 907 浏览 3 评论 0原文

这是我的情况:

我有艺术家和事件之间的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱花坊 2024-10-09 13:41:35

您可以将 Any 与“艺术家 ID”字段一起使用,此处假设名称为艺术家ID

_db.EventSet.Include("Location")
            .Where(e => (e.Artists.Any(a => a.ArtistId == artist.ArtistId)) && (e.StartDate > System.DateTime.Now))
            .OrderBy(e => e.StartDate);

You can use Any with the Artist ID field, here assuming a name of ArtistId:

_db.EventSet.Include("Location")
            .Where(e => (e.Artists.Any(a => a.ArtistId == artist.ArtistId)) && (e.StartDate > System.DateTime.Now))
            .OrderBy(e => e.StartDate);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文