Similar to 'Dynamic LINQ OrderBy' I would like to make a dynamic QueryOver-OrderBy. However, when I do this:
query.OrderBy(h => h.GetType().GetProperty(sort.Member).GetValue(h, null)).Asc
I get an exception which says:
Unrecognised method call in epression h.GetType().GetProperty(value(Domain.Model.Repository+<>c__DisplayClass15).sort.Member).GetValue(h, null)
Apparently, nHibernate has some trouble understanding what's going on. Does anyone have an idea on how to solve this particular issue?
The solution in the linked question doesn't work as there still is a problem when multiple entities are joined and sorting should be done on a combination of properties from different entities. The only practical solution I could think was to create a dictionary from sort.Member
to a Projection.Property
.
var dict = new Dictionary<string, string>();
dict.Add("sortMember", "entityAlias.Property");
var sortOn = dict[sort.Member];
query.OrderBy(Projections.Property(sortOn)).Asc;
This works quite well. The dictionary basically replaces the whole if-else construction and a simple loop adds the orderBy. I guess I can modify the filtering-part in a similar fashion, but haven't had time to work on that part yet.
Dynamic QueryOver doesn't make much sense.
QueryOver itself is strongly-typed Criteria. Use Criteria instead of QueryOver.
You should use the method you've presented in that "Dynamic Linq OrderBy" link. The problem in your code is that NHibernate can't parse that expression.
Also, I don't really understand why you're trying to sort by the value inside the property and not the property itself.
Assuming you're trying to sort by the property name all you need to do is:
1 - add a "using" for the extension method in your link
2 - use it like:
query.OrderBy(sort.Member);
Haven't tried it, but should work.