Search code examples
c#entity-frameworkreflectionentity

Reflection in Entity Framework C#


I am trying to use reflection to make a dynamic select through Entity Framework.

The idea is that the method will get as parameters the column name, the value for each column to search and the order of each column.

For example:

 public anEntity list(String ColumnName, String Value, String Order)
 {
    //
    //...
    items = (from r in context.Products
             where r.GetType().GetProperty(ColumnName). Contains(Value)))
             select r).OrderBy(Order).ToList();
    returns Items
 }

Is it possible? Could you help me?


Solution

  • I had the same thing! Spent 3 hours and found the solution!

    Expression.Lambda and query generation at runtime, simplest "Where" example

    It's very good work with EF, and Expression>, and LinqKit.

    Change code, for using dynamic types:

    private Expression<Func<Goods, bool>> LambdaConstructor (string propertyName, string inputText, Condition condition)
        {
    
                var item = Expression.Parameter(typeof(Goods), "item");
                var prop = Expression.Property(item, propertyName);
                var propertyInfo = typeof(Goods).GetProperty(propertyName);
                var value = Expression.Constant(Convert.ChangeType(inputText, propertyInfo.PropertyType));
                BinaryExpression equal;
                switch (condition)
                {
                    case Condition.eq:
                        equal = Expression.Equal(prop, value);
                        break;
                    case Condition.gt:
                        equal = Expression.GreaterThan(prop, value);
                        break;
                    case Condition.gte:
                        equal = Expression.GreaterThanOrEqual(prop, value);
                        break;
                    case Condition.lt:
                        equal = Expression.LessThan(prop, value);
                        break;
                    case Condition.lte:
                        equal = Expression.LessThanOrEqual(prop, value);
                        break;
                    default:
                        equal = Expression.Equal(prop, value);
                        break;
                }
                var lambda = Expression.Lambda<Func<Goods, bool>>(equal, item);
                return lambda;
            }
    

    And for OrderBy using: Unable to sort with property name in LINQ OrderBy