gpt4 book ai didi

c# - mongodb 驱动程序 c# - 过滤器表达式中的反射

转载 作者:可可西里 更新时间:2023-11-01 10:09:09 26 4
gpt4 key购买 nike

我正在尝试使用反射在 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}) is not supported.

我是不是做错了什么或者这种方法不能被遵循?

最佳答案

您不能在 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);

关于c# - mongodb 驱动程序 c# - 过滤器表达式中的反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com