Use WhereIf, IncludeIf, … to Improve Development Effectiveness

EntityFramwork: Improve Development Effectiveness with WhereIf, IncludeIf …

EntityFramwork: Improve Development Effectiveness with WhereIf, IncludeIf …

Background

Had you ever built your code like this?

I know it works very well, and I saw these kinds of code many times in different companies.

But my question is:

Could It Be Nicer?

Sure. Actually we have to handle with this kinds of logic every day. Why not try something different?

Let’s build an extentions class EnumerableExtensions.cs first:

public static class QueryableExtentions
{
public static IEnumerable<TSource>
WhereIf<TSource>
(this IEnumerable<TSource> source,
bool condition,
Func<TSource, bool> predicate)
{
return condition
? source.Where(predicate)
: source;
}
}

It’s simple. Actually the only difference with the original Where clause is the new parameter bool condition, which is used to decide if use Where or not.

Ok. Now let’s update the method FindAll with it.

public IQueryable<Products> FindAll(bool? active = null)
{
return db.Products.WhereIf(active != null, p => p.active == active);
}

Much simpler! Isn’t it?

Further Improvements

I reckon you must be thinking about something more: probably it could be applied to other clauses as well. Yes, you’re right.

I’ve built one with IncludeIf and AsNoTrackingIf, which are used widely. If you’re interested, please visit: https://dotnetfiddle.net/mfQUaG

Hope it helps. Enjoy!

Full Stack Developer (specialised in .NET Core, Angular and ReactJS)