I'm trying to build a filter for a MongoDB Collection in c# with Reflection.
IQueryable<Notification> collQuery = collection.AsQueryable()
.Where(entity =>
entity.GetType().GetProperty(filterProp.Name).GetValue(entity) == filter.FilterValue);
but when I call
collQuery.ToList()
I receive
{document}.GetType().GetProperty("SenderName").GetValue({document}) is not supported.
Am I doing something wrong or this approach cannot be followed?
You can not use reflection inside IQueryable expression, but you can use it to create expression manually. Use thid method:
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);
}
Now it is possible to apply it like this:
var where = CreateWherExpression(filterProp.Name, filter.FilterValue);
IQueryable<Notification> collQuery = collection
.AsQueryable()
.Where(where);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With