Error When Querying For A Substring Using Dynamic Linq

c# dynamic-linq entity-framework linq sql

Question

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"?

1
3
8/24/2016 11:04:14 PM

Accepted Answer

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")
2
8/25/2016 1:38:19 AM

Popular Answer

I feel misconception here... You are not supposed to use LINQ like this. As a start you need to invoke the overloads that accept lambdas; then you specify the property in the lambda and if its a string you invoke Contains on it. Like so:

var people = personContext
    .People
    .Where(p => p.Id.Contains("15"))
    .OrderByDescending(p => p.Id)
    .Skip(0) // You don't need this line.
    .Take(5)
    .ToList();

The EF itself will do the heavy lifting and translate these pure C# codes into the correct SQL statements.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow