Click here to Skip to main content
14,937,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
IQueryable<T> query = _dbContext.Set<T>();

if (includes != null)
{
    foreach (var includeProperty in includes)
    {
        query = includeProperty(query);
    }
}

return query;


What I have tried:

includes.Aggregate(_dbContext.Set<T>(), (current, includeProperty) => current(includeProperty))
Posted
Updated 5-Mar-21 0:28am

Why would you? The code works, and is simple and obvious what it does making it very supportable, so why change it?

Converting it to LINQ is not really going to change anything. LINQ is still going to use an enumerator over a collection to do a small job.

It sounds like you're converting it to LINQ just for the sake of using LINQ. That's not a good enough reason to use it.
   
Comments
BillWoodruff 3-Mar-21 15:58pm
   
+5
Maciej Los 5-Mar-21 7:16am
   
5ed!
Dave is correct - you are converting working code to LINQ just for the sake of it.

If you still want to use LINQ here, you will need to change your code to:
C#
IQueryable<T> query = (includes ?? Enumerable.Empty<Func<IQueryable<T>, IQueryable<T>>>()).Aggregate(_dbContext.Set<T>().AsQueryable(), (current, include) => include(current));
Breaking that down:

Your original code indicates that includes could be null. If it is, calling the Aggregate extension method on it will throw an ArgumentNullException. You need to provide a default value instead. Based on the usage, I have assumed the variable is a list of functions which take an IQueryable<T> and return the updated IQueryable<T>:
C#
includes ?? Enumerable.Empty<Func<IQueryable<T>, IQueryable<T>>>()

The accumulator function needs to return the same type as the seed argument. At the moment, seed is DbSet<T>, whereas your accumulator function returns IQueryable<T>. Add .AsQueryable() to your seed argument to correct the type:
C#
.Aggregate(_dbContext.Set<T>().AsQueryable(), 

The second argument to the accumulator function will be your include object. Based on the code usage, this is a function which transforms an IQueryable<T> instance. You are trying to pass this function to the IQueryable<T> accumulator, rather than passing the accumulator to the function.
C#
(current, include) => include(current)

As you can see, the resulting LINQ code is less readable, and considerably harder to debug. As Dave said, stick with your existing code instead.
   
Comments
Maciej Los 5-Mar-21 7:16am
   
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900