Entity Framework: Use Expression Trees to Build Dynamic Queries or Filter using Expression tree


Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries. Entity Framework or LINQ to SQL operates with expression trees to construct SQL queries from lambda expressions.

Look at below syntax:

void Delete<T>(Expression<Func<T, bool>> expression) where T : class, new()

A “predicate” is any device that says “yes” or “no” to the question “is this thing a member of that set?” So a predicate for the set “integers even positive integers” would be x=> x > 0 && x % 2 == 0.

This method probably has the semantics of “delete from the collection all members of the collection that are in the set identified by the predicate”.  The predicate is passed to the method in the form of an expression tree, which is a way of passing the structure of the predicate in a manner that can be analyzed at runtime and transformed.

  • Use Expression<Func<EntityName, bool>> rather than Expression<Predicate<EntityName>>, because that’s what Queryable.Where expects
  • Pass it directly in .Where, combining them using multiple .Where calls instead of &&.Unfortunately there’s no way to use Predicate<T> in EF linq since it’s impossible to map it on SQL query. This can be done with Expressions only because they can be parsed and converted to SQL.In fact there are 4 language features that made linq possible:
    1. Extension methods
    2. Type inference
    3. Closures
      and for linq2sql especially
    4. Expressions

    Code Example

public Course EditCourse(Course obj)
   return courseRepo.Update(obj, x => x.CourseId == obj.CourseId);
public virtual T Update(T obj, Expression<Func<T, bool>> match)
     using (var context = new PluralSightContext())
        if (obj == null)
           return null;
         T existing = context.Set<T>().SingleOrDefault(match);
         if (existing != null)
         return existing;

So now map Expression<Func<T, bool>> in above example: bool is return type and T refers to Course Entity, so Expression x => x.CourseId == obj.CourseId stores the info about that expression and that there’s a T x, that you’re accessing the property CourseId (T corresponds to Course entity)

Calling the == operator with the int value provided by user. When EF looks at that, it might turn it into something like [Course_Table].[CourseID_Column] == parameter value

MSDN Reference Link

MSDN Reference Link2



3 thoughts on “Entity Framework: Use Expression Trees to Build Dynamic Queries or Filter using Expression tree

  1. rededeeventos

    Greetings from Idaho! I’m bored to tears at
    work so I decided to browse your website on my iphone during lunch
    break. I enjoy the information you present here and can’t wait to take a look when I get home.
    I’m shocked at how fast your blog loaded on my
    cell phone .. I’m not even using WIFI, just 3G .. Anyhow, fantastic blog!


  2. Lazaro

    Hey There. I found your blog using msn. This is a very well written article.

    I will be sure to bookmark it and come back
    to read more of your useful information. Thanks for the post.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s