我有一个带有儿童收藏价格的课程产品:
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>
您可以看到价格收集已经延迟加载。
产品从数据库加载如下:
public ICollection<Product> ListProducts()
{
ISession session = GetCurrentSession();
return session
.CreateCriteria(typeof(Product))
.List<Product>();
}
该函数引用GetCurrentSession(),它具有以下内容:
protected ISession GetCurrentSession()
{
return sessionProvider.GetCurrentSessionFrom(sessionFactoryConfigName);
}
当我加载产品时,我希望产品中Price-Collections的位置是代理,因为价格有lazy-loading = true。但在调试时,使用Visual Studio监视工具,我可以查看产品,并可以查看具有完整内容的价格集合(具有所有属性的价格)。为什么会这样?
答案 0 :(得分:3)
因为VS总是触发价格的getter方法,而价格反过来会加载价格为零的所有价格。 如果您正在使用SQL Server并想要检查延迟加载是否按预期工作,请使用SQL Server Profiler(如果您使用的是Express版,请使用AnjLab SqlProfiler)。
答案 1 :(得分:2)
由于您在调试时访问了Price属性,因此代理将加载产品集合... 这意味着,您通过“观察”价格属性触发了延迟加载过程。
您可以通过配置nhibernate来查看会发生什么,以便输出已执行的SQL语句(show_sql配置选项)。