0

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?

Paolo
  • 631
  • 2
  • 10
  • 23

1 Answers1

3

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

Community
  • 1
  • 1
Eldho
  • 7,795
  • 5
  • 40
  • 77
  • Thancks Eldho for your answer, your solution of course works but using anonymous types you are changing the domain and that's not exaclty smart cause than it is necessary to cast all objects to the right domain. – Paolo Nov 22 '15 at 13:34
  • @Zeta you could project directly to `your viewmodel` instead of anonymous projection. Try this `Select(p=> new YourModel{ ParentItems = p, ChildItems= p.ChildItems}).ToList();` https://documentation.devexpress.com/#WPF/CustomDocument17979 – Eldho Nov 23 '15 at 06:22
  • Using a predicate in the `.Select()` function the sql code generated is affected filtering all the childItems just as I need. Following my example in the root question the code would be: `context.MyEntity.Include( myentity => myentity.navigationPropertyCollection ).Select( myentity => myentity.navigationPropertyCollection.Where( n => m.IsActive()) ); ` – Paolo Dec 03 '15 at 13:51
  • I think it works same as the above code. `Select()` is a `IQuerable` extension so you could add you query to the database. – Eldho Dec 03 '15 at 13:59