entity framework linq

Handling wildcard characters in queries is vital for flexible and efficient search functionality. In this article, we’ll explore how to build a wildcard-enabled LINQ query for Entity Framework utilizing extension methods and expression trees.

Entity Framework Supported String Methods

Entity Framework provides several methods from the System.String class that support wildcard searching and can be transformed into SQL. These methods include:

  • Contains(string value)
  • StartsWith(string value)
  • EndsWith(string value)

A simple example of using wildcard search is as follows:

var q = (from c in db.Customers
where c.CompanyName.Contains(name)
select c)

However, to give users more control over the match method, we can allow them to supply wildcard characters at the beginning or end of the text. To achieve this, we’ll need to dynamically build a query based on the presence and location of these wildcard characters.

Utilizing Expression Trees and Extension Methods

To avoid writing repetitive code and enhance reusability, we can use expression trees and extension methods. Here’s the code for the extension methods that can be utilized in future queries:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class LinqExtensions
public static IQueryable WhereLike(
this IQueryable source,
Expression> valueSelector,
string value,
char wildcard)
return source.Where(BuildLikeExpression(valueSelector, value, wildcard));

public static Expression<Func<TElement, bool>> BuildLikeExpression<TElement>(
    Expression<Func<TElement, string>> valueSelector,
    string value,
    char wildcard)
    if (valueSelector == null)
        throw new ArgumentNullException("valueSelector");

    var method = GetLikeMethod(value, wildcard);

    value = value.Trim(wildcard);
    var body = Expression.Call(valueSelector.Body, method, Expression.Constant(value));

    var parameter = valueSelector.Parameters.Single();
    return Expression.Lambda<Func<TElement, bool>>(body, parameter);

private static MethodInfo GetLikeMethod(string value, char wildcard)
    var methodName = "Contains";

    var textLength = value.Length;
    value = value.TrimEnd(wildcard);
    if (textLength > value.Length)
        methodName = "StartsWith";
        textLength = value.Length;

    value = value.TrimStart(wildcard);
    if (textLength > value.Length)
        methodName = (methodName == "StartsWith") ? "Contains" : "EndsWith";
        textLength = value.Length;

    var stringType = typeof(string);
    return stringType.GetMethod(methodName, new Type[] { stringType });


By leveraging extension methods and expression trees, we can create a more maintainable and reusable solution for building wildcard-enabled LINQ queries in Entity Framework.