mercredi 1 août 2018

Creating a LINQ to SQL compatible expression that accesses a property by its name

I was wondering if any of you has an idea on how to tackle this problem.

Suppose there's the following class

public class Person
{
    public string Description {get; set;}
    //...
}

I'd like to create an expression that can be passed in to LINQ's Where method in LINQ's Where method in LINQ to SQL, such as the following:

Expression<Func<Person, bool>> expression = x => x.Description.Contains("foo");

The real problem here is that I don't know what field is going to be checked until runtime. The name of the property is provided as a string (in this case it would be "Description", but it can be "Description2", or any other property of the Person class). I can't use reflection directly in the expression itself to get the property value (by using GetType, GetProperty etc.) because the expression won't work when passed to Where in LINQ to SQL because it can't be translated to an SQL code. Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire