1

I have this scenario:

class A
{
    public virtual int Id { get; set; }
    public virtual B Child { get; set; }
}

class B
{
    public virtual int Id { get; set; }
}

In the mapping of class A, I have a reference to class B:

map.Reference(a => a.Child).LazyLoad();

Now when I do something like:

Session.Query<TypeOfA>().Select(a => a);

Apart from the normal select * from ATable I get n selects from the BTable for each A line. Is like lazy loading is not working.

My questions are:

  1. How to I make the lazyload work here ?
  2. Can I bring the A entities and B entities in a single query ?

Thank you,

Calin
  • 6,661
  • 7
  • 49
  • 80

2 Answers2

3

Lazy loading is switched on by default and should actually work. If there would be a problem, for instance if it can't generate the proxy for class B, it would complain when creating the session factory.

Are you sure that the queries for B are done by the query itself, and not be subsequent access to A?

You could optimize the access to B in two ways: fetch them together with A in a single query. (I don't know fluent, this is the xml way to configure it:)

<many-to-one fetch="join" ...>

This has some problems when used with lists and could also blow up your query a lot. It is of course not lazy loading at all.

Another, very nice and powerful optimization is batch fetching. It allows the instances to be fetched in separate queries, but fetches several of them at once.

<class name="B" batch-size="20" ...>

This would fetch 20 B's at once in one query. It is also available for lists:

<one-to-many fetch-size="20" ...>
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
  • @Tom: This is not true. There is *anohter* batch-size, which can be set in the configuration and uses batching of ADO.NET. It makes NH create batches when flushing the session, for update and insert statements. It is only available for Sql Server. (See http://ayende.com/Blog/2006/09/16/BatchingSupportInNHibernate.aspx). But the batch-size I'm talking about is for queries and is database independent. – Stefan Steinegger Nov 30 '10 at 06:53
  • my mistake - I deleted my comment. – Tom Bushell Nov 30 '10 at 20:37
  • @Tom: the problem is that NH uses ambiguous terms sometimes. it makes understanding the features very hard. – Stefan Steinegger Dec 02 '10 at 13:42
  • yeah, this leads to a steep learning curve. But once you've climbed it, the payoff is major. – Tom Bushell Dec 02 '10 at 21:00
  • @ToM: yes, it is worth the effort, but it could be easier sometimes if the terms were clearer. – Stefan Steinegger Dec 03 '10 at 07:53
0

Expanding on Stafan's suggestion to use batch-size, a quick Google search reveals that Fluent NHibernate now supports BatchSize for queries. From the docs:

ClassMap<T> BatchSize(int size) 

Sets the query batch size for this entity.

Never used it myself, and the documentation is minimal (like a lot of FNH), but maybe you can find some sample code.

Tom Bushell
  • 5,865
  • 4
  • 45
  • 60