Reputation: 31
I am trying to store all associations/joins for an ORM in a list of
public class OrmJoin{
public Type Type1 { get; set;}
public Type Type2 { get; set;}
public bool IsRequired { get; set;}
public Expression<Func<object, object, bool>> Predicate { get; set;}
}
Can I then loop through this list and convert the Predicate property into
Expression<Func<T1,T2,bool>>
by somehow converting the first 2 object expression parameters into typed parameters using typeof(Type1)
and typeof(Type2)
?
Upvotes: 0
Views: 309
Reputation: 14477
Here is how you can do it:
public class OrmJoin
{
// ...
public Expression AsTyped()
{
var parameters = new[] { Type1, Type2 }
.Select(Expression.Parameter)
.ToArray();
var castedParameters = parameters
.Select(x => Expression.Convert(x, typeof(object)))
.ToArray();
var invocation = Expression.Invoke(Predicate, castedParameters);
return Expression.Lambda(invocation, parameters);
}
public Expression<Func<T1, T2, bool>> AsTyped<T1, T2>() => (Expression<Func<T1, T2, bool>>)AsTyped();
}
void Main()
{
var test = new OrmJoin { Type1 = typeof(string), Type2 = typeof(int), Predicate = (a,b) => Test(a,b) };
var compiled = test.AsTyped<string, int>().Compile();
Console.WriteLine(compiled.Invoke("asd", 312));
}
bool Test(object a, object b)
{
Console.WriteLine(a);
Console.WriteLine(b);
return true;
}
Upvotes: 1