Entity Framework Core: Is there a way to reuse sub query instead of Include without DRY?

Viewed 209

I have a couple of queries, and I am wondering if I can reuse one query and deconstruct it to be reused in another query, which should include the same navigational properties.

var personQuery = query
                   .Include(entity => entity.Location)
                   .ThenInclude(entity => entity.City)
                   .Include(entity => entity.Qualifications)
                   .ThenInclude(entity => entity.Degree)
                   .Include(entity => entity.Professions)
                   .ThenInclude(entity => entity.Industry)

var profileQuery = query
                       .Include(arg => arg.Person) //Need to include personQuery navigations properties here
                       .Include(arg => arg.User)    

I use these two queries in two different calls, these only defines the selection and navigational properties to include for those.

I want to include the navigational properties in Profile.Person and if I do that, I would have to maintain two different queries for Profile and Person with same navigations properties defined twice

So, Profile query would become

                var profileQuery = query
                   .Include(arg => arg.Person) 
                   .ThenInclude(entity => entity.Location)
                   .ThenInclude(entity => entity.City)
                   .Include(arg => arg.Person) 
                   .ThenInclude(entity => entity.Qualifications)
                   .ThenInclude(entity => entity.Degree)
                   .Include(arg => arg.Person) 
                   .ThenInclude(entity => entity.Professions)
                   .ThenInclude(entity => entity.Industry) 
                   .Include(arg => arg.User)

Is there a way I can use (or reuse) GetPersonQuery without having to define the Person navigations properties twice and maintaining the same query in two different ways. I understand the complexity of the problem, ProfileQuery Person be IIncludableQueryable<Profile, Person> (IQueryable) and GetPersonQuery is IQueryable, I am wondering if there is anything I am unaware of that would help me with this particular predicament. Shouldn't I be able to define navigation properties somewhere and reuse them by rewriting both Queries which would have common navigational properties?

I am surprised there isn't already something that could help me out with this, or am I just living under a self-isolated rock?

If I don't include additional navigations includes in Profile and reuse the PersonQuery I would just have to run multiple queries.

Any middle ground/best compromise I can get?

Any help would be appreciated, thanks in advance.

0 Answers
Related