我正在使用 NHibernate 3.3.3.4001。我遇到一个问题,NHibernate 在发出 Get 请求时不会延迟加载数据。相反,它填充整个对象模型,导致性能非常慢。 .hbm 文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="My.Assembly" namespace="Assembly.Model">
<class name="Parent" table="tblParent">
<id name="ID">
<generator class="native"></generator>
</id>
<version name="Version" column="Version"/>
<component name="Children">
<bag name="Collection" table="tblChildren"
cascade="save-update, merge" inverse="true">
<key column="ParentID"></key>
<one-to-many class="Children"></one-to-many>
</bag>
</component>
<property name="DateCreated" column="DateCreated" update="false" insert="false" />
<property name="Inactive" column="Inactive" />
</class>
</hibernate-mapping>
我原本期望 NHibernate 延迟加载所有子对象而不向数据库发送查询。我尝试添加显式的 lazy = true
和 default-lazy=true
但没有什么区别。我检查了 Config
对象,可以看到映射具有 islazy=true
。
我按如下方式调用 Get:
using (var transaction = Session.BeginTransaction())
{
t = Session.Get<T>(id);
transaction.Commit();
}
我很困惑为什么这不是延迟加载而是在数据库中查询所有子对象?
最佳答案
不确定我是否理解你的真正目标。上面代码片段中的组件内容是否完整?或者只是一个缩短版本?
无论如何,如下所述:5.1.13. component, dynamic-component (引用)
The
<component>
element maps properties of a child object to columns of the table of a parent class....
因此,背后的想法主要是从 C# 角度将其用作引用对象,同时将其存储在一个表中。示例7.1. Dependent objects
<class name="Eg.Person, Eg" table="person">
<id name="Key" column="pid" type="string">
<generator class="uuid.hex"/>
</id>
<property name="Birthday" type="date"/>
<component name="Name" class="Eg.Name, Eg">
<parent name="NamedPerson"/> <!-- reference back to the Person -->
<property name="Initial"/>
<property name="First"/>
<property name="Last"/>
</component>
</class>
因为实体看起来像这样:
public class Person
{
...
public virtual Name Name { get; set; }
public class Name
{
public virtual Person NamedPerson { get; set; }
public virtual string Initial { get; set; }
...
所以,如果你的情况是 child <component>
实际上只是一个集合 - 不要使用上面的映射,而是像这样:
父级:
<class name="Parent" table="tblParent">
<id name="ID" generator="native" />
<version name="Version" column="Version"/>
<!-- just a bag -->
<bag name="Children" table="tblChildren" cascade="save-update, merge" inverse="true">
<key column="ParentID"></key>
<one-to-many class="Child"></one-to-many>
</bag>
<property ...
</class>
child :
<class name="Child" table="tblChildren">
...
<many-to-one name="Parent" column="ParentID" />
...
和 C#:
public class Parent
{
public virtual IList<Child> Children { get; set; }
...
public class Child
{
public virtual Parent Parent { get; set; }
...
所有加载肯定都会很懒惰。
关于c# - NHibernate 不延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23699517/