Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb driver c# - reflection in filter expression

Tags:

c#

mongodb

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?

like image 830
gizu00 Avatar asked May 01 '26 07:05

gizu00


1 Answers

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);
like image 101
Aleks Andreev Avatar answered May 02 '26 19:05

Aleks Andreev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!