What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

Saturday, February 1, 2014

Invoking IDbSet<T>.FirstOrDefault(predicate) using reflection

 

Assuming you have a data context with a property of IDBSet<Person> and person has a property called Id, you can issue:

var person = context.PersonDbSet.FirstOrDefault(i=>i.Id=3);

here’s how you do it with reflection:

Assuming you have a reference to your data set, called dbset

Begin with defining the predicate (the where statement)

ParameterExpression parameter = Expression.Parameter(entityType, "Id");
MemberExpression property = Expression.Property(parameter, 3);
ConstantExpression rightSide = Expression.Constant(refId);
BinaryExpression operation = Expression.Equal(property, rightSide);
Type delegateType = typeof (Func<,>).MakeGenericType(entityType, typeof (bool));
LambdaExpression predicate  = Expression.Lambda(delegateType, operation, parameter);

 

Now a reference to the extension method:

    var method = typeof (System.Linq.Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public)
                .FirstOrDefault(m => m.Name == "FirstOrDefault" && m.GetParameters().Count() == 2);

   MethodInfo genericMethod = method.MakeGenericMethod(new[] { entityType });            

 

Finally execute the method:

object retVal = genericMethod.Invoke(null, new object[] {dbSet, predicate});

Posted On Saturday, February 1, 2014 3:15 PM | Comments (0) |

Powered by: