1

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?

Community
  • 1
  • 1
Pieter
  • 3,237
  • 4
  • 27
  • 59

3 Answers3

2

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.

Pieter
  • 3,237
  • 4
  • 27
  • 59
0

Dynamic QueryOver doesn't make much sense.

QueryOver itself is strongly-typed Criteria. Use Criteria instead of QueryOver.

Diego Mijelshon
  • 51,805
  • 14
  • 112
  • 150
  • I'm using the strongly-typed features of QueryOver to build the main part of the query. It's just that filtering and sorting ideally needs to be dynamic as these instructions come from the GUI. I can write a big if-else, but a more generic solution using reflection would be nicer imho. – Pieter Nov 02 '11 at 09:08
0

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.

psousa
  • 6,565
  • 1
  • 29
  • 43