我正在尝试使用反射功能在c#中为MongoDB集合构建过滤器。
IQueryable<Notification> collQuery = collection.AsQueryable()
.Where(entity =>
entity.GetType().GetProperty(filterProp.Name).GetValue(entity) == filter.FilterValue);
但是当我打电话
collQuery.ToList()
我收到
{document} .GetType()。GetProperty(“ SenderName”)。GetValue({document})。
我做错了什么还是无法遵循这种方法?
答案 0 :(得分:2)
您不能在IQueryable
表达式中使用反射,但是可以使用它手动创建表达式。使用thid方法:
public static Expression<Func<Notification, bool>> CreateWherExpression(
string propertyName, string filterValue)
{
var notificationType = typeof(Notification);
var entity = Expression.Parameter(notificationType, "entity");
var body = Expression.Equal(
Expression.Property(entity, propertyName),
Expression.Constant(filterValue));
return Expression.Lambda<Func<Notification, bool>>(body, entity);
}
现在可以像这样应用它:
var where = CreateWherExpression(filterProp.Name, filter.FilterValue);
IQueryable<Notification> collQuery = collection
.AsQueryable()
.Where(where);