Im not used to working with expression funcs, but my problem is: I get the name of a property as a string, i then need to convert this to the appropriate expression.
Currently im doing something like this:
if (string.Equals(propertyString, "customerNo", StringComparison.InvariantCultureIgnoreCase))
{
return _repo.DoSomething(x=>x.CustomerNo);
}
if (string.Equals(propertyString, "customerName", StringComparison.InvariantCultureIgnoreCase))
{
return _repo.DoSomething(x => x.CustomerName);
}
With the repo function something like this:
public IEnumerable<ICustomer> DoSomething(Expression<Func<IObjectWithProperties, object>> express)
{
//Do stuff
}
What i would like to do, is use reflection like this:
var type = typeof(IObjectWithProperties);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if(string.Equals(property.Name,propertyString,StringComparison.InvariantCultureIgnoreCase))
return _repo.DoSomething(x => x.PROPERTY);
}
But I can't figure out a way to generate the expression func from the propertyinfo
EDIT: Mong Zhu's answer, i am able to create an expression using the property.
The reason i need this expression, is that im trying to dynamically set the orderby in an iqueryable.
public IEnumerable<Customer> List(Expression<Func<IObjectWithProperties, object>> sortColumn)
{
using (var context = _contextFactory.CreateReadOnly())
{
return context.Customers.OrderBy(sortColumn).ToList();
}
}
Using the answer like this:
public Customer Test(string sortColumn){
var type = typeof(IObjectWithProperties);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (string.Equals(property.Name, sortColumn, StringComparison.InvariantCultureIgnoreCase))
{
Expression<Func<IObjectWithProperties, object>> exp = u =>
(
u.GetType().InvokeMember(property.Name, BindingFlags.GetProperty, null, u, null)
);
return _customerRepository.List(exp);
}
}
}
I get an error:
System.InvalidOperationException : variable 'u' of type 'IObjectWithProperties' referenced from scope '', but it is not defined
EDIT:
The Customer return type inherits the IObjectWithProperties:
public class Customer: IObjectWithProperties
{
//properties
}