Orphu.of.io
Orphu.of.io

Reputation: 125

Using a dynamic value for the Model property in a Lambda expression

I'm trying to dynamically generate a model property in my Lambda express. In my controller I have the following method:

public ActionResult FilterSubCategory(string filter, string selected)
{
    IList<Item> model = db.Items.Where(p => p.Make == selected).ToList();
    var viewModel = Mapper.Map<IList<ItemViewModel>>(model);
    return View("~/Views/Phone/Index.cshtml", viewModel);
}

I want to use this method to filter my page's column so I'm passing the filter(model property to filter) and the actual selected property value.

I want to replace the 'Make' ('hardcoded' here) here with the value of the filter string passed. Is there a way to do this?

Upvotes: 2

Views: 2289

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30607

This is what I do:

public static Expression<Func<TModel, TProperty>> GenerateModelExpression<TModel, TProperty>(PropertyInfo property)
{
     ParameterExpression fieldName = Expression.Parameter(typeof(TModel), "m");

     var propertyExpr = Expression.Property(itemExpr, property.Name);

     return Expression.Lambda<Func<TModel, TProperty>>(propertyExpr, fieldName);
}

The property parameter would be 'Make' in your case which you can get using reflection.

https://github.com/AmmarCSE/razor-grid

Edit

After reviewing the question more precisely and referencing former answery by @Servy, How do i create the following LINQ expression dynamically?, here is a solution:

public static Expression<Func<TModel, TProperty>> GenerateModelExpression<TModel, TProperty>(string filter, string select)
{
     ParameterExpression param = Expression.Parameter(typeof(TModel), "m");
     var body = Expression.Equal(Expression.Property(param, typeof(TModel).GetProperty(filter))
      , Expression.Constant(select));

     return Expression.Lambda<Func<TModel, TProperty>>(body, param);
}

Upvotes: 1

Related Questions