如何强制NHibernate不更新集合中的所有对象 [英] How to force NHibernate not to update all objects in collection

查看:53
本文介绍了如何强制NHibernate不更新集合中的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果仅更改集合中的每个元素,如何强制NHibernate不为集合中的每个元素生成UPDATE.在这里:

How to force NHibernate not to generate UPDATE for each element in collection if I change only one element of that collection. Here it is:

internal class Master
{
    private int _id;

    public string Name { get; set; }
    public ISet<Slave> Slaves { get; set; }

    public Master()
    {
        Slaves = new HashedSet<Slave>();
    }
}

internal class Slave
{
    private int _id;

    public string Name { get; set; }
    public Master Master { get; set; }
}

映射:

<class name="nHibernateTutorials.Slave, nHibernateTutorials" lazy="false">
    <id access="field" name="_id" column="id">
        <generator class="native"/>
    </id>
    <property access="property" name="Name" column="name"/>
    <many-to-one access="property" name="Master" column="master"/>
</class>

<class name="nHibernateTutorials.Master, nHibernateTutorials" lazy="false">
    <id access="field" name="_id" column="id">
        <generator class="native"/>
    </id>
    <property access="property" name="Name" column="name"/>
    <set access="property" name="Slaves" cascade="save-update">
        <key column="master"/>
        <one-to-many class="nHibernateTutorials.Slave, nHibernateTutorials"/>
    </set>
</class>

用于更新集合元素的代码:

Code that updates collection element:

Master m = new Master {Name = "Kenny"};

Slave s1 = new Slave { Name = "Cartman", Master = m};
m.Slaves.Add(s1);
Slave s2 = new Slave {Name = "Kyle", Master = m};
m.Slaves.Add(s2);
Slave s3 = new Slave {Name = "Stan", Master = m};
m.Slaves.Add(s3);

DbManager.SaveObject(m);

s1.Name = "Daisy";
DbManager.SaveObject(m);

DbManager.SaveObject中的代码只是打开新会话并使用SaveOrUpdate来更新对象.

Code in DbManager.SaveObject simply opens new session and uses SaveOrUpdate to update object.

如果我更改master的Slaves集合中的元素之一,然后尝试更新master,则NHibernate会生成SQL以更新Slaves集合中的所有元素.但是我只需要更新一个元素.

If I change one of the elements from the Slaves collection of master and then try to update master, NHibernate generates SQL for updating all elements in Slaves collection. But I need to update only one element.

谢谢.

推荐答案

您可能会看到多余的多对一更新.在映射一对多集合时,必须选择关系的所有者.在您的示例中,双方的双方都认为自己拥有它!

You're probably seeing superfluous many-to-one updates. When you're mapping one-to-many collections, you must choose which side is the owner of the relationship. In your example, both sides of the relationship think they own it!

您需要使用inverse="true"将属性添加到您的set元素中.该指令告诉NHibernate不要从关系的那一端开始更新集合.

You need to add an attribute to your set element, with inverse="true". That directive tells NHibernate not to update the collection from that end of the relationship.

这篇关于如何强制NHibernate不更新集合中的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆