Expression<Func<T, bool>>


Overview

When working with an ORM like Entity-Framework this can be incredibly useful for building dynamic queries from an entity in a function. It allows you to pass a function as a parameter and have that function be executed on the entity. I need to credit a fellow student who I had the priviledge of working with at Penn State on my Capstone project for this one.

The benefit of this is that it is type specific so when writing code you will have intellisense available. Additionally, you can create extremely dynamic queries with a few lines of code. This example assumes the use of Entity Framework Core, although it can be adapted to nearly any ORM relatively easily.

Code

public IQueryable Search(Expression<Func<Users, bool>> predicate)
{
    return _context.Users.Where(predicate);
}

Usage

Find All Users With Bio
IQueryable<Users> results = userRepository.Search(u => u.Bio != null);
Returns
All users who have a complete bio.