简体   繁体   中英

How to convert Linq Expression<Func<object,object,bool>> to Expression<Func<T1,T2,bool>>

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) ?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM