lundi 11 juin 2018

C# - Order By property by reflection [duplicate]

This question already has an answer here:

I have a database query providing me IQueryable object where T is anonymous data type like this:

var baseListQuery = (<...> select new {
    note = n, // class Note
    triggers = grp // class Trigger
})

Now I would like to sort this by different properties of Note (e.g. Note.Title) but my Note class can contain plenty of different properties. Property to be used as sorting element can be changed externaly and information about which one to use I will receive as a simple string. Currently I am using switch-case statement to evaluate received string and then select appropriate property to sort:

switch(SortBy) {
    ...
    case "Title": baseListQuery = baseListQuery.OrderBy(p => p.note.Title); break;
    ...
}

However, I am wondering if it is possible to to it in more general way, using reflection? I would like to check if Note contains property with the name of received string and if so, sort results appropriately. I have tried something like this:

var baseQueryType = baseListQuery.GetType();
var member = (baseQueryType.GetGenericArguments()[0]).GetProperty("note");
var member2 = member.PropertyType.GetProperty("Title"); // I would like to use GetProperty(SortBy);
baseListQuery = baseListQuery.OrderBy(p => member2);

Which will raise exception when calling for example baseListQuery.Count():

System.NotSupportedException: 'Unable to create a constant value of type 'System.Reflection.PropertyInfo'. Only primitive types or enumeration types are supported in this context.'

Is it possible to do this with reflection, and if so, can somebody explain me, what am I doing wrong?





Aucun commentaire:

Enregistrer un commentaire