Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to set parameter of method using reflection
    primarykey
    data
    text
    <p>The following code is a helper I've created for a system which allows administrators to create their own queries on a database. It returns a lambda expression based on the method and value provided.</p> <p>I am attempting to find a way to pass parameters to the method call - in this example I am using the <code>StartsWith</code> parameter of <code>String</code>, and attempting to set <code>StringComparison.OrdinalIgnoreCase</code> as a parameter. </p> <p>There will be others parameters required too, depending on the type of the property specified. I'm hoping that understanding the method of supplying the string comparison property will enable me to add the rest later.</p> <p>The underlying code works correctly, I just need it to be case-insensitive.</p> <p>I have used <a href="https://stackoverflow.com/questions/2202381/reflection-how-to-invoke-method-with-parameters">this question</a> as a guide, but the solution does not seem applicable here.</p> <p>Here is the code:</p> <pre><code>public static class LambdaExpressionHelper&lt;T&gt; { public static Expression&lt;Func&lt;T, bool&gt;&gt; Build(string propertyName, string method, string propertyValue) { PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName); ParameterExpression e = Expression.Parameter(typeof(T), "e"); MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo); ConstantExpression c = Expression.Constant(propertyValue, m.Type); MethodInfo mi = m.Type.GetMethod(method, new Type[] { m.Type }, ); // The below caused errors //object classInstance = Activator.CreateInstance(typeof(T), null); //object[] paramArray = new object[] { StringComparison.OrdinalIgnoreCase }; //mi.Invoke(classInstance, paramArray); Expression call = Expression.Call(m, mi, c); Expression&lt;Func&lt;T, bool&gt;&gt; lambda = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(call, e); return lambda; } } // External code: var lambda = LambdaExpressionHelper&lt;MailingListMember&gt;.Build("EmailAddress", "StartsWith", "RoRy@"); </code></pre> <p>Thanks for any help.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload