简体   繁体   English

在Lambda表达式中为Model属性使用动态值

[英]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. 我正在尝试在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. 我想使用此方法来过滤页面的列,因此我要传递filter(要过滤的模型属性)和实际的选定属性值。

I want to replace the 'Make' ('hardcoded' here) here with the value of the filter string passed. 我想用传递的过滤器字符串的值替换“ Make” (此处为“硬编码”)。 Is there a way to do this? 有没有办法做到这一点?

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. 在您的情况下,属性参数将为“ Make”,您可以使用反射来获取。

https://github.com/AmmarCSE/razor-grid 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? 在更精确地审查了问题并通过@Servy引用以前的答案后, 如何动态创建以下LINQ表达式? , 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM