简体   繁体   English

过滤实体框架 6 中包含的元素

[英]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.我正在尝试使用 Entity Framework 6 来获取 Person 实体的集合,其中包含延迟加载的 TimeTrack 实体集合。 I only want to include the TimeTrack entities, where the Start property is in a specified period.我只想包括 TimeTrack 实体,其中 Start 属性位于指定时间段内。 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?有什么方法可以过滤查询中的 TimeTracks 吗?

As you noticed, EF 6 doesn't support to filter in the Include method.如您所见,EF 6 不支持在Include方法中进行过滤。

Disclaimer : I'm the owner of the project Entity Framework Plus免责声明:我是Entity Framework Plus项目的所有者

The EF+ Query IncludeFilter (free and open source) allows easily filter included entities. EF+ Query IncludeFilter (免费和开源)允许轻松过滤包含的实体。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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