5

I'm using NHibernate with FluentNH. I've a simple class called PostCategory and it contains a collection of Posts. The PostCategory class contains a property called TotalActivePosts. When I load all the PostCategories I want the no. of active posts for each category to be populated in this property. How I can do that? Any help is greatly appreciated.

Vijaya Anand

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275

2 Answers2

3

The way I did it is by using a computed property. see item no. 5- arbitrary SQL.
you could use something like:

Select Count(*) from Posts where PostCategoryId = Id And IsActive = 1    

see also this question

Community
  • 1
  • 1
J. Ed
  • 6,692
  • 4
  • 39
  • 55
3

You can either do what sJhonny recommends or use the lazy="extra" attribute on the mapping. That way you can just do Posts.Count to get just the count without loading all of the entities.

See this SO question: NHibernate Lazy="Extra"

Community
  • 1
  • 1
Vadim
  • 17,897
  • 4
  • 38
  • 62
  • I'm using Fluent NHibernate. How and where I can specify this lazy="extra"? (NOTE: Currently many classes I'm using extra properties like TotalPosts, TotalComments that are tied with formulas in classes to know the count of child collections without loading them entirely. If I can avoid them using the lazy="extra" feature it is really great!) – Vijaya Anand May 15 '11 at 13:27
  • I wasn't aware of that option. nice.. although Jaguar mentions there that it's not an 'official' feature of the lazy="extra" option, and he found it to be buggy. so, perhaps it should be used with caution. – J. Ed May 15 '11 at 13:27
  • 1
    @Vijaya `HasMany(p => p.Posts).ExtraLazyLoad()` – Vadim May 15 '11 at 19:11