2

In my repositories, I find that the WhereIf Linq-to-sql extension from this thread (LINQ to SQL Where Clause Optional Criteria) is very useful -- especially the IEnumerable version.

I would like to do the same thing with the Include() statement, but I'm not very good with writing extensions. I got stuck on the declaration of the extension.

Can anyone help me port the WhereIf extension to IncludeIf?

Community
  • 1
  • 1

1 Answers1

4

There are two Include(...), one that is already an extension method to IQueryable<T> and one that is a method of DbQuery<T>. This should give you both extensions IncludeIf<>

public static class QueryableEx
{
    public static IQueryable<T> IncludeIf<T, TProperty>(this IQueryable<T> source, bool condition, Expression<Func<T, TProperty>> path) where T : class
    {
        if (condition)
        {
            return source.Include(path);
        }
        else
        {
            return source;
        }
    }

    public static DbQuery<TResult> IncludeIf<TResult>(this DbQuery<TResult> query, bool condition, string path)
    {
        if (condition)
        {
            return query.Include(path);
        }
        else
        {
            return query;
        }            
    }
}

Remember that you need to put them in a static class like I have done.

xanatos
  • 109,618
  • 12
  • 197
  • 280