Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Expression.Call overloads?

I was attempting to dynamically create a Where predicate for a LINQ2SQL query:

...Where(SqlMethods.Like(r.Name, "%A%") ||
         SqlMethods.Like(r.Name, "%B%") ||
         SqlMethods.Like(r.Name, "%C%") || ...)

A, B, C, etc. come from some array. So I tried the following:

var roleExpression = Expression.Parameter(typeof(Role), r);
var nameExpression = Expression.Property(roleExpression, "Name");
var termExpression = Expression.Constant("%" + term[i] + "%");
var likeExpression = Expression.Call(
    typeof(SqlMethods), "Like",
    new[] { typeof(string), typeof(string) }, nameExpression, termExpression);

However, the last line fails with the message No method 'Like' on type 'System.Data.Linq.SqlClient.SqlMethods' is compatible with the supplied arguments.

So I tried the following line:

var likeExpression = Expression.Call(null,
    typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }),
    nameExpression, searchTermExpression)

This works. However, I don't understand what the difference is between these two lines. In my opinion they should deliver the same result.

Could anyone explain this?

Kind regards,
Ronald Wildenberg

like image 686
Ronald Wildenberg Avatar asked Mar 10 '09 08:03

Ronald Wildenberg


1 Answers

I believe that the Type[] argument is for generic type parameters - i.e. you were trying to call:

SqlMethods.Like<string,string>(...); // note the <string,string>

Try passing an empty Type[].


Edit re the confusion (comments); my point is: you shouldn't be specifying anything for the Type[] argument. Either an empty array or null would do; for example:

var likeExpression = Expression.Call(
    typeof(SqlMethods), "Like", null, nameExpression, termExpression);
like image 157
Marc Gravell Avatar answered Nov 19 '22 14:11

Marc Gravell