Recently I have started profiling my application and found that there is a great performance hit when I am trying to get Count of elements of a lazy collection. For example if I had such mapping:
Code:
<class name="Foo" lazy="false">
<bag name="BarList" table="Bar" inverse="true" cascade="all-delete-orphan" lazy="true" batch-size="100">
<key column="FooId"></key>
<one-to-many class="Bar"/>
</bag>
</class>
And tries to execute code like:
Code:
int elementsCount = Foo.BarList.Count;
Then the profile data shows me that it takes about 180 ms to execute. There is no doubt that NHibernate tries to get the data from the database and after that it gets count of elements.
Is there a way to optimize this behavior? I don't want to write custom queries just to get a count of elements in a collection. Is there is a way to instruct NHibernate to load all element Ids even when using lazy load? So it would look like the collection already has all elements (which are actually proxies, but contains real object ids) and calling Count didn't force database query?