【问题标题】:Need explanation on NHibernation lazy loading需要解释 NHibernation 延迟加载
【发布时间】:2011-01-07 12:58:14
【问题描述】:

我有一个带有子集合价格的类产品:

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 的位置是代理,因为价格具有延迟加载 = true。但是在调试时,使用 Visual Studio 监视工具,我可以查看产品并可以查看包含全部内容的价格集合(价格及其所有属性)。为什么会这样?

【问题讨论】:

    标签: .net nhibernate lazy-loading


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      因为 VS 总是触发 Prices 的 getter 方法,如果价格为空,它会依次加载所有价格。 如果您使用 SQL Server 并想检查延迟加载是否按预期工作,请使用 SQL Server Profiler(如果您使用的是 Express 版本,请使用 AnjLab SqlProfiler)。

      【讨论】:

      • 或者使用Nhiberante在log4net中记录的sql语句
      猜你喜欢
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2014-01-19
      • 2011-02-27
      • 1970-01-01
      • 2013-11-23
      • 2011-09-24
      • 1970-01-01
      相关资源
      最近更新 更多