开发者

Need explanation on NHibernation lazy loading

I have a class product with child collection prices:

public class Product
{
    private ICollection<Price> prices;

    protected Product()
    {
        prices = new List<Price>();
    }
}

The NHibernate mapping looks like this

<xml version="1.0" encoding="utf-8">
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="Product" table="Product">

    <id name="id" column="ProductId" access="field">
        <generator class="identity"/>
    </id>

            <bag name="prices" access="field" cascade="all-delete-orphan"  lazy="true">
        <key column="ProductId"/>
        <one-to-many class="Product.Price"/>
    </bag>

        </class>

You can see that the prices-collection is lazily loaded.

Products are loaded like this from database:

public ICollection<Product> ListProducts()
    {
        ISession session = GetCurrentSession();

        return session
            .CreateCriteria(typeof(Product))
            .List<Product>();
    }

The function refers on GetCurrentSession(), which has the following content:

protected ISession GetCurrentSession()
    {
         return sessionProvider.GetCurrentSessionFrom(sessionFactoryConfigName);
    }

When I load products, I would expect that on the place of the Price-Collections in the products is a proxy because the prices have lazy-loading = true. But while debugging, with the Visual Studio watch tool I can view the products and can s开发者_开发知识库ee the prices-collection with full content (Prices with all their properties). Why is this so?


Since you've accessed the Prices property while debugging, the proxy will have loaded the products collection ... That means, you've triggered teh lazy loading processs by 'watching' the Prices property.

You can see what happens by configuring nhibernate so that the SQL Statements that are executed, are outputted (show_sql configuration option).


because VS always triggers the getter method of Prices, which in turn loads all prices in case prices is null. If you are using SQL Server and want to check if lazy loading is working as expected, use SQL Server Profiler (Use AnjLab SqlProfiler in case you are using Express edition).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜