动态成员表达式
我想创建一个只知道字段名称的 MemberExpression;例如:
public static Expression<Func<TModel, T>> GenerateMemberExpression<TModel, T>(string fieldName)
{
PropertyInfo fieldPropertyInfo;
fieldPropertyInfo = typeof(TModel).GetProperty(fieldName);
var entityParam = Expression.Parameter(typeof(TModel), "e"); // {e}
var columnExpr = Expression.MakeMemberAccess(entityParam, fieldPropertyInfo); // {e.fieldName}
var lambda = Expression.Lambda(columnExpr, entityParam) as Expression<Func<TModel, T>>; // {e => e.column}
return lambda;
}
上面的问题是字段类型必须是强类型的。将“对象”作为字段类型传递是行不通的。有什么办法可以生成这个吗?甚至动态 LINQ 似乎也不起作用。
I am wanting to create a MemberExpression knowing only the field name; eg:
public static Expression<Func<TModel, T>> GenerateMemberExpression<TModel, T>(string fieldName)
{
PropertyInfo fieldPropertyInfo;
fieldPropertyInfo = typeof(TModel).GetProperty(fieldName);
var entityParam = Expression.Parameter(typeof(TModel), "e"); // {e}
var columnExpr = Expression.MakeMemberAccess(entityParam, fieldPropertyInfo); // {e.fieldName}
var lambda = Expression.Lambda(columnExpr, entityParam) as Expression<Func<TModel, T>>; // {e => e.column}
return lambda;
}
The problem with the above is that the field type must be strongly typed. Passing "object" in as the field type doesn't work. Is there any way to generate this? Even Dynamic LINQ doesn't appear to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码存在许多问题:
fieldName
,但您却用它获取了一个属性。Expression.Lambda
方法来生成表达式,如果传递给该方法的类型参数T
不是,则该表达式可能会选择不合适的委托类型。与属性类型相同。在这种情况下,从表达式到方法的返回类型的as
转换将失败并计算为null
。解决方案:使用 通用Lambda
方法适当的类型参数。无需铸造。Expression.Convert
方法。以下是解决这些问题的示例更新:
这将使以下所有调用成功:
There are a number of issues with your code:
fieldName
, but you are getting a property out with it.Expression.Lambda
method to generate the expression, which may choose an inappropriate delegate-type if the type-argumentT
passed to the method is not the same as the property-type. In this case, theas
cast from the expression to the method's return-type will fail and evaluate tonull
. Solution: Use the genericLambda
method with the appropriate type-arguments. No casting required.T
, but not when more complicated conversions such as boxing / lifting are required. Solution: Use theExpression.Convert
method where necessary.Here's an update to your sample that addresses these issues:
This will make all of the following calls succeed:
如果传递“对象”,请尝试手动转换字段值。例如:
希望这对您有帮助。
Try manually converting the field value in case of passing an "object". For example:
Hope this will help you.