I'd like to create a query contains User
whose entities has Event
with type == 1
. I would also like the Event
entries loaded into EventsCollection
. My code would be something like .Include(u => u.EventsCollection)
, but this only loads all Event
entries - I want to load only with type == 1.
I have simple model like this:
public class User
{
public int UserId { get; set; }
public ICollection<Event> EventsCollection { get; set; }
}
public class Event
{
public int EventId { get; set; }
public int UserId { get; set; }
public int Type { get; set; }
public User User {get; set; }
}
Any ideas?
Edit:
Finally I've found the solution: We need fresh DataContext object with NO Event entities have been previously loaded.
Then we need to filter Events like this:
var filteredEventsCollection = db.Events
.Where(ev => ev.Type == 1)
.ToList(); //Materialize query here
Now we should query users like this:
var usersWithFilteredEvents = db.Users
.Where(u => u.EventsCollection.Any(ev => ev.Type == 1))
.ToList();
And that is all! EF will substitute EventsCollection with data from the first query by itself.