Search code examples
c#sqlentity-frameworklinqdynamic-linq

Error When Querying For A Substring Using Dynamic Linq


I'm trying to use dynamic linq to obtain a subset of people from a database using Entity Framework (EF). I'm running into a problem when using the contains operation. Here is the entity for the People table:

public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

Here is a query that works successfully.

var people = personContext
    .People
    .OrderBy("id asc")
    .Skip(0)
    .Take(5)
    .ToList();

Notice that I'm using dynamic linq in the OrderBy method. However, when I try to apply filtering, I get an exception.

var people = personContext
    .People
    .Where("id.Contains(15)")
    .OrderBy("id asc")
    .Skip(0)
    .Take(5)
    .ToList();

What I'd like to get back is a subset of people with ids that contain the substring "15", such as:

"015", "115", "151", "152", etc.

When I execute the code, I get the following error.

System.Linq.Dynamic.ParseException was unhandled by user code
    Message=No applicable method 'Contains' exists in type 'String'

What is the syntax for determining if the Id field contains the string "15"?


Solution

  • What is the syntax for determining if the Id field contains the string "15"?

    Well, definitely not .Where("id.Contains(15)") which is trying to invoke the method Contains with numeric value 15.

    According to the documentation, you can use either a string literal:

    .Where("id.Contains(\"15\")")
    

    or substitution values:

    .Where("id.Contains(@0)", "15")