Using Contains in ObjectQuery
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 f开发者_开发问答ollows:
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.
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);
精彩评论