I am using Ladislav Mrnka’s extension method:
public static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query,
params Expression<Func<T, object>>[] includes)
where T : class
{
if (includes != null)
{
query = includes.Aggregate(query,
(current, include) => current.Include(include));
}
return query;
}
I took the following method from Here (after little change):
public virtual IEnumerable<T> Get(
Expression<Func<T, bool>>[] filters = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = "")
{
IQueryable<T> query = GetQuery();
if (filters != null)
{
foreach (var filter in filters)
{
query = query.Where(filter);
}
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
query = orderBy(query);
}
return query;
}
I want to use the IncludeMultiple instead of strings in includeProperties variable.
So, I changed the function:
public virtual IEnumerable<T> Get(
Expression<Func<T, bool>>[] filters = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = GetQuery();
if (filters != null)
{
foreach (var filter in filters)
{
query = query.Where(filter);
}
}
if (includes.Length > 0)
{
query = query.IncludeMultiple(includes);
}
if (orderBy != null)
{
query = orderBy(query);
}
return query;
}
Now, I am a little bit confuse. This method defined in a class where GetQuery() is defined (repository implementation). But in case I want to execute this method, I would have initially use GetQuery()..
Am I right?
Is it better to use this as an extension to IQueryable?
No you don’t need to use this method after you call
GetQuerybecause callingGetQueryis the first command in this method. You can use eitherGetQueryorGetdepending on your needs. TheGetmethod is actually very good because it hides including. Using it as a repository method is much better then using it as extension method in case of unit testing and mocking.