级联错误:具有相同标识符值的不同对象已与会话关联
我有一个由 NHibernate 实现并使用延迟加载的项目。 我在这个项目中有两个课程:个人和家庭。 这两者之间的关系是聚合,意味着一个人有一个家庭列表。 映射是:
<class name="Person" table="Person_Person" >
<id name="Id" type="Int64" unsaved-value="0">
<generator class="native" />
</id>
<bag name="Families" inverse="true" table="Person_Family" cascade="all-delete-orphan" >
<key column="Person_id_fk"/>
<one-to-many class="Domain.Entities.Family,Domain.Entities"/>
</bag>
</class>
在这个项目中,我通过 ID 获取一个人,然后更新一个家庭成员。
Person person = SessionInstance.Get<Person>(id);
foreach (Family fam in person.Families)
if (fam.Name == "Jaun")
{
fam.Code = 100;
SessionInstance.Update(fam);
}
该系列未更新,因为此消息引发异常: `具有相同标识符值的不同对象已与会话关联:193,实体:Domain.Entities.Family
我如何更新一个人的家庭?
I have a project by NHibernate implementation and using Lazy Loading.
I have two class in this project : Person and Family.
Relation between Those two is aggregation, is mean a Person has a list of Family.
Mapping is :
<class name="Person" table="Person_Person" >
<id name="Id" type="Int64" unsaved-value="0">
<generator class="native" />
</id>
<bag name="Families" inverse="true" table="Person_Family" cascade="all-delete-orphan" >
<key column="Person_id_fk"/>
<one-to-many class="Domain.Entities.Family,Domain.Entities"/>
</bag>
</class>
In this project, I Get a person by ID then update a family of families person.
Person person = SessionInstance.Get<Person>(id);
foreach (Family fam in person.Families)
if (fam.Name == "Jaun")
{
fam.Code = 100;
SessionInstance.Update(fam);
}
The family not updated, Because throw a exception by this message :
`a different object with the same identifier value was already associated with the session: 193, of entity: Domain.Entities.Family
How can i update a family of person?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的情况下,您不需要调用
Update
。您只需要刷新会话即可。在你的情况下,我会做这样的事情:或者你可以做这样的事情:
ISession.Update() 用于更新
分离
对象。在你的情况下,该对象没有分离。您应该阅读 NHibernate 文档中的以下 2 部分,以便更好地理解这一点:http://www.nhforge.org/doc/nh/en/index.html#manipulateddata-updating-insession
http://www.nhforge.org/doc/nh /en/index.html#manipulateddata-updating-detached
In your case here you do not need to call
Update
. You just need to flush the session. In your case I would do something like this:Or you can do something like this:
ISession.Update() is meant for updating
detached
objects. In your case the object is not detached. You should read the following 2 sections in the NHibernate documenation to have a better understanding of this:http://www.nhforge.org/doc/nh/en/index.html#manipulatingdata-updating-insession
http://www.nhforge.org/doc/nh/en/index.html#manipulatingdata-updating-detached
尝试更新人员对象而不是家庭对象。
try to update person object instead of family object.