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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With