筛选器表达式中的 MongoDB 驱动程序反射



我正在尝试使用反射为c#中的MongoDB集合构建过滤器。

IQueryable<Notification> collQuery = collection.AsQueryable()
.Where(entity =>
entity.GetType().GetProperty(filterProp.Name).GetValue(entity) == filter.FilterValue);

但是当我打电话时

collQuery.ToList()

我收到

{文档}。GetType((。GetProperty("SenderName"(.不支持 GetValue({document}(。

我做错了什么还是无法遵循这种方法?

不能在表达式中使用反射IQueryable但可以使用它来手动创建表达式。使用方法:

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);

最新更新