2011-01-07 59 views
0

我有一个一流的产品与子集合价格说明:需要对NHibernation延迟加载

public class Product 
{ 
    private ICollection<Price> prices; 

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

NHibernate的映射看起来像这样

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

你可以看到prices-收藏是懒惰加载。

产品加载像这样从数据库:

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

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

该功能是指上的getCurrentSession(),它具有以下内容:

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

当我加载的产品,我会期望在价格收集在产品中的位置是一个代理,因为价格具有延迟加载=真实。但是,在调试时,使用Visual Studio监视工具,我可以查看产品,并可以看到具有完整内容(包含所有属性的价格)的价格集合。这是为什么?

回答

2

由于您在调试时访问了Prices属性,代理将加载产品集合...... 这意味着,您已通过“观看”Prices属性触发了延迟加载过程。

您可以看到配置nhibernate发生了什么,以便输出执行的SQL语句(show_sql配置选项)。

3

因为VS总是触发价格的getter方法,在价格为空的情况下,这又会加载所有价格。 如果您正在使用SQL Server并希望检查延迟加载是否按预期工作,请使用SQL Server Profiler(如果使用Express版本,请使用AnjLab SqlProfiler)。

+0

或者在log4net中使用Nhiberante记录的sql语句 – Paco 2011-01-07 14:12:12