EntityFramework 5 filter an included navigation property

前端 未结 1 1604
死守一世寂寞
死守一世寂寞 2020-12-31 05:49

I would like to find a way using Linq to filter a navigation property to a subset of related entities. I know all answers around this subject suggest doing an anonymous sel

1条回答
  •  隐瞒了意图╮
    2020-12-31 06:29

    Anything even touching on this subject either has a cop-out "It can't be done" answer or no answer at all. Nothing is impossible... including this.

    Sure. It is possible. You can download EF source code and add this feature yourselves. It will be great contribution to open source project and the community. I believe EF team will gladly help you with your effort.

    With the current version "it can't be done" is the answer. You can either use projection to anonymous or special unmapped type as you have described in the beginning of your question. Other options are separate explicit query to load related entities for single parent or separate query to load related entities for all parents.

    Load relations for single parent:

    context.Entry(event)
           .Collection(e => e.Discussions)
           .Query()
           .Where(d => ...)
           .Load();
    

    Load relations for all parents (requires lazy loading to be turned off):

    // load all parents
    var events = query.Where(e => ...).ToList();
    
    // load child filtered by same condition for parents and new condition for children
    childQuery.Where(d => e.Event ... && d.Something ...).Load();
    

    The second solution requires child to have navigation property back to parent (for constructing same query condition used initially to loads parent). If you have everything correctly configured and entities are attached EF should automatically fix your relations (collections) in parent entities (but it will not mark collection in dynamic proxy as loaded so that is the reason why you cannot use this together with lazy loading).

    0 讨论(0)
提交回复
热议问题