开发者

Nhinerbate lazy loading of reference entity

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,


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" ...>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜