Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering navigation property in eager loading

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();

like image 806
RJardines Avatar asked Mar 25 '26 10:03

RJardines


1 Answers

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.

like image 89
Ladislav Mrnka Avatar answered Mar 28 '26 01:03

Ladislav Mrnka