Entity framework filter lambda navigation properti

2019-09-02 18:32发布

问题:

Using .NET Entity Framework 6 I need to filter the elements of an included virtual collection. What I mean is easily explained with the following code:

context.MyEntity.Include( navigationPropertyCollection => navigationPropertyCollection.Where( np => np.IsActive() ) )

the code code is just an example, to say from MyEntity I want include only active elements of navigationPropertyCollection.

Is there a smart way to do it?

回答1:

Note that it is not currently possible to filter which related entities are loaded. Include will always bring in all related entities.

msdn reference

you could try this by anonymous projection

var resultObjectList = _context.
                   Parents.
                   Where(p => p.DeletedDate == null).
                   OrderBy(p => p.Name).
                   Select(p => new
                             {
                                 ParentItem = p,
                                 ChildItems = p.Children.Where(c => c.Name=="SampleName")
                             }).ToList();

Similar Answer in Stack