Question

I want to receive sum of property in top 5 elements in linq to NHibernate query. If I use below code:

Session.Query<Document>().Take(5).Sum(x => x.Value)

I get 'method not supported' exception.

Any ideas?

NHibernate 3.3.1.4000

Was it helpful?

Solution

You can use this:

Session.Query<Document>().Select(x => x.Value).Take(5).Sum();

NHibernate only supports the Sum overload without an expression parameter.

And for unknown reasons you have to first Select and than Take as you correctly commented.

OTHER TIPS

The problem is that the provider isn't fully implemented yet. Try to materialise using .ToArray() to memory and then calculate .Sum() using linq-to-memory.

For example:

Session.Query<Document>().Select(x => x.Value).Take(5).ToArray().Sum()

ps: same kind of problems could happens with .Skip() and joins with DefaultIfEmpty()

In NHibernate.4.0.2.4000 the Sum with lambda works also Session.Query<Document>().Take(5).Sum(x => x.Value).

If it is possible to get no rows returned and Value is not a nullable type you need to cast it to a nullable type as the sum will return null when no items are present:

Session.Query<Document>().Take(5).Sum(x => (decimal?)x.Value) ?? 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top