1

I want to use a property of an entity model to filter the result;

This is the code I would normally use:

db.Users.Where(ent => ent.Id > 5).ToList();

But I can only access the property by its name as string ("Id") or by its ProperyInfo.

This is what I tried to use but it doesn't seem to work:

db.Users.Where(ent => (int) ent.GetType().GetProperty("Id").GetValue(ent,null) > 5).ToList();

Note that the where clause might get more complex, and I might use another property type (not int).

Alex Boicu
  • 53
  • 4

2 Answers2

1

Well one thing you can do is build the Where expression using the property name, eg:

public static Expression GreaterThanExpression<T>(string propertyName, object valueToCompare)
{
    var entityType = typeof(T);

    var parameter = Expression.Parameter(entityType, "entity");

    var lambda = Expression.Lambda(
            Expression.GreaterThan(
                Expression.Property(parameter, propertyName),
                Expression.Constant(valueToCompare)
            )
        , parameter);

    return lambda;
}

Then using this static method you can do the following in your query:

var result=b.Users.Where(GreaterThanExpression("Id",5)).ToList();

If you need to combine more than one expression, then you should take a look this post.

Community
  • 1
  • 1
ocuenca
  • 38,548
  • 11
  • 89
  • 102
0

You can use reflection and/or expression builders to dynamically create LINQ queries, but that is a slippery slope.

It's much simpler to just switch on the property name to apply the correct filter.

Example assuming that you have a string name and a string value that need to be converted to a LINQ query:

string name = "Id";
string value = "5";
switch (propertyName)
{
    case nameof(User.Id):
        var id = int.Parse(value);
        return db.Users.Where(ent => ent.Id > id).ToList();
    case nameof(User.Name):
        return db.Users.Where(ent => ent.Name == value).ToList();
}
Steven Liekens
  • 13,266
  • 8
  • 59
  • 85