'Executing linq lamda expression as parameter in System.Reflection Invoke Method calling
I'm trying to execute My GetSingleAsync method which comes with system reflection. But ı need to execute linq query when I'm invoking this method, in my researches ı mostly saw just single parameters,but ı need to execute linq expression in this method call.
Here is what I'm trying to get when ı execute:
var data = await repository.GetSingleAsync(record => record.date == StartDate.ToString("yyyy-MM-dd"));
Here is my current code try, i need to execute record => record.date == StartDate.ToString("yyyy-MM-dd") linq in question mark part:
dynamic repository = Activator.CreateInstance(RepositoryType);
MethodInfo GetSingleAsync = RepositoryType.GetMethod("GetSingleAsync");
var model = GetSingleAsync.Invoke(repository, ??); //need help in question mark?
Solution 1:[1]
Basically you need to look at the parameters of GetSingleAsync
. Assuming the parameter needs to be of type Func<T,bool>
then you need:
Func<T,bool> predicate = rec => rec.Property == someValue;
Your parameter is then
var model = GetSingleAsync.Invoke(repository, new []{ predicate });
Update: If you do not want to depend on some Type T you can construct your predicate using Expression API:
public static object SomePredicate(Type recordType, string propertyName, Expression comparisonValue) {
var parameterExpression = Expression.Parameter(recordType);
var propertyExpression = Expression.PropertyOrField(parameterExpression, propertyName);
var lambdaExpression = Expression.Lambda(Expression.Equal(propertyExpression, comparisonValue), parameterExpression);
return lambdaExpression.Compile();
}
You can then construct your predicates like so (if you have a type Repository with integer Property Record):
var somePredicate = SomePredicate(typeof(Repository), nameof(Repository.Record), Expression.Constant(5));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |