There are a few issues with the code.
- You're selecting
CategoryId
after filtering byCategoryId
. Did you mean to selectEventId
s instead? if(categoryList.Any())
should beif(categories.Any())
- There needs to be a lambda expression in
.Where(categoryList.Contains(categoryId))
Here's a revised version of the code that has a better chance of working...
var eventIdList = new List<int>();
var eventIds = context.CategoryEvents
.Where(c => c.CategoryId == categoryId)
.Select(c => c.EventId);
if(eventIds.Any())
{
eventIdList.AddRange(eventsIds);
}
var eventsInCategory = context.Events
.Where(e => eventIdList.Contains(e.EventId)); // or simply e.Id, depending on what your model looks like
If that works, there is a lot that can be done to improve/simplify the code.
For example, this if
block actually executes two database queries, once for Any()
and a second one during AddRange()
...
if(eventIds.Any())
{
eventIdList.AddRange(eventsIds);
}
You can actually replace the first chunk of code using ToList()
. There is no need for new List<int>()
, Any()
, or AddRange()
...
var eventIdList = context.CategoryEvents
.Where(c => c.CategoryId == categoryId)
.Select(c => c.EventId)
.ToList();
And it sounds like all you're trying to do with this entire piece of code is to find all events in a given CategoryId
. You can do this in 1 EF query...
var eventsInCategory = context.Events
.Join(context.CategoryEvents,
e => e.EventId, // or simply e.Id, depending on what your model looks like
ce => ce.EventId,
(e, ce) => e)
.ToList();
This can be further simplified if the models are set up with the proper navigation properties. For example, if you have a Categories
DbSet
and it has a navigation property for all related Event
s:
var eventsInCategory = context.Categories.Find(categoryId).Events;