Entity Framework include filter child collection

心已入冬 提交于 2019-11-30 19:38:47

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

EF+ Query IncludeFilter feature allows filtering related entities.

var item = _Context.Order
           .IncludeFilter(x => x.Inner.Where(y => y.IsDeleted))
           .IncludeFilter(x => x.Inner.Where(y => y.IsDeleted).Select(y => y.first))
           .IncludeFilter(x => x.Inner.Where(y => y.IsDeleted).Select(y => y.second))
           .Where(x => ( !(x.IsDeleted) && (x.IsActive) && 
                 (x.itemid == id))).FirstOrDefault();

Note: You cannot mix Include & IncludeFilter.

Wiki: EF+ Query IncludeFilter

EDIT: Answer sub-question

But we can achieve this using EF only

Yes, under the hood, my library uses a similar solution as projection

var item = _Context.Order.Select(x => new {
                Order = x,
                Inner = x.Inner.Where(y => y.IsDeleted),
                first = x.Inner.Where(y => y.IsDeleted).Select(y => y.first)
                second = x.Inner.Where(y => y.IsDeleted).Select(y => y.second)
            })
            .Where(x => ( !(x.IsDeleted) && (x.IsActive) && (x.itemid == id)))
            .FirstOrDefault()
            .Select(x => x.Order)
            .FirstOrDefault();

Note: Code have not been tested

EDIT: Answer comment

I came across this issue in EF Core. Are you going to implement IncludeFilter also in the EF+Core version

Starting from the v1.10.0, the IncludeFilter is now supported in EF Core 2.x

See: Release Note

I was able to achieve this in EF Core. I'm pretty sure the same concept applies in EF6.

Simplifying your example:

var item = ctx.Order.Include("Inner")
              .Where(x => x.Inner.Any(innerItem => innerItem.IsDeleted))
              .FirstOrDefault();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!