3

I have been working with soft delete and now i want to load the navigation properties of my entity that are not "deleted". I have found a way, my problem this way is not to clear for me, there is another way to do this.

Context.CreateSet().Include("Salary").Select(u => new {User= u, Salary = u.Salarys.Where(s => !s.Deleted)}).AsQueryable().Select(a => a.User).AsQueryable();

RJardines
  • 850
  • 9
  • 18
  • There is a working soft delete solution here: http://stackoverflow.com/questions/12698793/soft-delete-entity-framework-code-first/18985828#18985828 – Colin Dec 03 '13 at 22:39

1 Answers1

4

Eager loading doesn't support filtering. Your code can be simplified to:

var users = Context.CreateSet<User>()
                   .Select(u => new {
                       User = u,
                       Salary = u.Salaries.Where(s => !s.Deleted)
                    })
                    .AsEnumerable()
                    .Select(a => a.User);

Include is not needed because you are replacing it with your own query and AsQueryable is not needed because the query is IQueryable all the time till called AsEnumerable which will sqitch to Linq-to-Objects when selecting users and selected salaries. EF will take care of correctly fixing navigation properties for you.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • This is the current solution, thanks, but EF doesn't support something more clear, this look like a trick. – RJardines Oct 21 '12 at 10:23
  • Yes it is a trick because filtering navigation properties [is not supported](http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015345-allow-filtering-for-include-extension-method). – Ladislav Mrnka Oct 21 '12 at 11:00
  • This solution need to be modified if salaries is a many to many relation? I test it in and dont work in a new use case where user tried to filter a navigation property having a many to many relation – RJardines May 10 '13 at 16:03