mongodb驱动程序c#-过滤器表达式中的反射
我正试图用c#和反射为MongoDB集合构建一个过滤器mongodb驱动程序c#-过滤器表达式中的反射,c#,mongodb,C#,Mongodb,我正试图用c#和反射为MongoDB集合构建一个过滤器 IQueryable<Notification> collQuery = collection.AsQueryable() .Where(entity => entity.GetType().GetProperty(filterProp.Name).GetValue(entity) == filter.FilterValue); 我收到 不支持{document}.GetType().GetProperty(
IQueryable<Notification> collQuery = collection.AsQueryable()
.Where(entity =>
entity.GetType().GetProperty(filterProp.Name).GetValue(entity) == filter.FilterValue);
我收到
不支持{document}.GetType().GetProperty(“SenderName”).GetValue({document})
是我做错了什么,还是无法遵循此方法?您不能在
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);
}
public静态表达式CreateWherExpression(
string propertyName、string filterValue)
{
var notificationType=类型(通知);
var实体=表达式.参数(notificationType,“实体”);
var body=表达式。等于(
Expression.Property(实体,propertyName),
常量(filterValue));
返回表达式.Lambda(body,entity);
}
现在可以这样应用它:
var where = CreateWherExpression(filterProp.Name, filter.FilterValue);
IQueryable<Notification> collQuery = collection
.AsQueryable()
.Where(where);
var where=CreateWherExpression(filterProp.Name,filter.FilterValue);
IQueryable collQuery=集合
.AsQueryable()
.何处;
var where = CreateWherExpression(filterProp.Name, filter.FilterValue);
IQueryable<Notification> collQuery = collection
.AsQueryable()
.Where(where);