c# NHibernate -访问一个元素's列表抛出错误(未能惰性初始化…)
本文关键字:错误 出错 列表 初始化 访问 NHibernate 一个 元素 | 更新日期: 2023-09-27 18:14:02
我使用的是MVC2, NHibernate 3.2.
我的类:
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(typeof(EstoqueEquipamento).Assembly);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
我用this来查询元素:
public Car GetCar(object pk)
{
using (ISession session = NHibernateHelper.OpenSession())
{
return session.Get<Car>(pk);
}
}
Car映射:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateClasses" namespace="NHibernateClasses.Entities">
<class name="Car" table="STACK.CAR" lazy="true" dynamic-update="true" dynamic-insert="true" >
<id name="CarId" column="CAR_ID" type="Int32" unsaved-value="0">
<generator class="sequence">
<param name="sequence">SQ_CAR</param>
</generator>
</id>
<bag name="TireList" inverse="true" generic="true" lazy="true" >
<key>
<column name="CarId"/>
</key>
<one-to-many class="Tire" />
</bag>
<property name="Plate" type="String" column="MAH_PLATE" />
</class>
</hibernate-mapping>
轮胎映射:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateClasses" namespace="NHibernateClasses.Entities">
<class name="Tire" table="STACK.Tire" lazy="true" dynamic-update="true" dynamic-insert="true" >
<id name="TireId" column="Tire_ID" type="Int32" unsaved-value="0">
<generator class="sequence">
<param name="sequence">SQ_Tire</param>
</generator>
</id>
<property name="Brand" type="String" column="MAH_BRAND" />
</class>
</hibernate-mapping>
然后我查询元素:
var car = GetCar(1);//works just fine
var tirelist = car.Tires;//throws error!
第一行没有问题,但最后一行抛出以下错误:
[汽车]初始化失败惰性初始化role集合:的车。TireList,没有会话或会话已关闭
如果你还需要配置文件,请告诉我。
谢谢
在GetCar中,您在稍后在代码中访问tire集合之前关闭会话(由于using
)。在nHibernate中,集合默认是惰性加载的,所以确保在结束事务之前获取集合。你可以使用Eager loading来确保nHibernate也加载子集合