简体   繁体   中英

Filter included elements in entity framework 6

I am trying to use Entity Framework 6 to get a collection of Person entities, that contains a lazy loaded collection of TimeTrack entities. I only want to include the TimeTrack entities, where the Start property is in a specified period. The code below does what i want, but is not effective.

    private async Task<List<Person>> GetPersonsWithTimetracksForPeriod(int companyId, DateTime from, DateTime to)
    {
        // Repository.AsQueryable() gets context.AsQueryable() with the wanted type
        var query = Repository.AsQueryable().Where(e => e.CompanyId == companyId).Include(p => p.TimeTracks);
        var persons = await query.ToListAsync();
        // Another way of filtering TimeTracks is needed
        foreach (var person in persons)
        {
            person.TimeTracks = person.TimeTracks.Where(t => t.Start >= from && t.Start <= to).ToList();
        }
        return persons;
    }

Is there any way to filter the TimeTracks in the query?

As you noticed, EF 6 doesn't support to filter in the Include method.

Disclaimer : I'm the owner of the project Entity Framework Plus

The EF+ Query IncludeFilter (free and open source) allows easily filter included entities.

To use it, you simply need to replace all "Include" by "IncludeFilter".

Example:

private async Task<List<Person>> GetPersonsWithTimetracksForPeriod(int companyId, DateTime from, DateTime to)
{
    var query = Repository.AsQueryable().Where(e => e.CompanyId == companyId)
                   .IncludeFilter(p => p.TimeTracks.Where(tt => t.Start >= from && t.Start <= to);

    var persons = await query.ToListAsync();

    return persons;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM