3

I have an entity ("A") that I'm persisting via NHibernate. This entity might have several children of type ("B") in the database, and when I retrieve entity A, I want to have a property that indicates a count of entity B that belong to A. I don't want to use a collection here because I don't have to have to retrieve all B entities just to count them.

Psuedo SQL to do what I want might look like:

select a.*, count(b.*) from a left join b on b.aid = a.id

Is this possible with NHibernate, and specifcally the LINQ provider?

Chris
  • 27,596
  • 25
  • 124
  • 225
  • 1
    Duplicate: http://stackoverflow.com/questions/3062850 – brainimus Apr 07 '11 at 18:58
  • possible duplicate of [Use SQL query to populate property in nHibernate mapping file](http://stackoverflow.com/questions/3062850/use-sql-query-to-populate-property-in-nhibernate-mapping-file) – Chris Apr 07 '11 at 19:25

3 Answers3

3

If you specify in your collection lazy="extra", when you access the count property on the collection nhibernate will just get the count of the children rather than all of the children.

See here (2nd heading): http://blog.idm.fr/2010/02/improving-performance-with-nhibernate.html

Vadim
  • 17,897
  • 4
  • 38
  • 62
1

Can you bind your nHibernate to a view instead?

CREATE VIEW A_augmented
AS
SELECT A.*
       ,(SELECT COUNT(*) FROM B WHERE B.aid = a.id) AS ChildCount
FROM A

(I know this SQL is relatively naive, but it is about as simple a way of expressing it in valid SQL)

Cade Roux
  • 88,164
  • 40
  • 182
  • 265
1

You could use Formula to map a property to an SQL expression. There is an example of the very problem on Ayendes site. Nice to use, but may have side-effects you need to be avare of. The calculated column is of course not up to date. It is a snapshot when the entity is loaded.

You could also use HQL to get the size with a simple syntax:

select a, size(a.Children)
from a

Of course this also returns a snapshot, but your business logic is aware of that and therefore it is not a side-effect.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193