Elnoor
Elnoor

Reputation: 3752

Reflection within IQueryable in .NET Core

I am wondering how would the below code work and what would be the performance. I am interested in line #4 basically. How will linq and property info work together?

In other words will (int)prop.GetValue(a) and a.SomeId work the same way or will the reflection need to get everything to memory before checking the value?

var prop = type.GetProperty("SomeId");

if (prop != null) 
{
     DbSet<T> dbSet = _dbContext.Set<T>();
     return dbSet.Where(a => (int)prop.GetValue(a) == 1);
}

Upvotes: 1

Views: 355

Answers (1)

Nkosi
Nkosi

Reputation: 247123

In other words will (int)prop.GetValue(a) and a.SomeId work the same way

No.

Depending on the backing store, the context may fail to convert that expression ((int)prop.GetValue(a)) to the underlying query syntax, which in most cases would be SQL.

You could consider building a valid expression manually using the property info.

For example

//Assuming
Type type = typeof(T);

PropertyInfo prop = type.GetProperty("SomeId");
if (prop != null) {
    //need to build a => a.SomeId == 1

    // a =>
    ParameterExpression parameter = Expression.Parameter(type, "a");
    // a => a.SomeId
    MemberExpression property = Expression.Property(parameter, prop);
    // a => a.SomeId == 1
    BinaryExpression body = Expression.Equal(property, Expression.Constant(1));

    Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(body, parameter);

    DbSet<T> dbSet = _dbContext.Set<T>();

    return dbSet.Where(expression);
}

Upvotes: 2

Related Questions