如何在nhibernate中保存分配了ID的孩子 [英] How to save a child with assigned id in nhibernate

查看:101
本文介绍了如何在nhibernate中保存分配了ID的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两节课:

public class Parent
{
    public virtual long? ID { get; set; } // native
    public virtual IList<Child> Children { get; set; }
    public virtual string Name { get; set; }
}

public class Child
{
    public virtual long ID { get; set; } // assigned
    public virtual string Name { get; set; }
}

实例化并保存父级和子级:

Instantiating and saving parent and child:

child = new Child() { ID = 1, Name = "SomeName" };
parent = new Parent() { Children = new List() { child } };
session.Save(parent);

哪个给我:

NHibernate.StaleStateException:意外的行数:0;预期:1.

我认为问题出在给孩子分配的ID上.由于它具有ID,因此NHibernate认为它以前已经保存过,而事实并非如此.

I think the problem is with the assigned id on the child. Since it has an id, NHibernate thinks it has previously saved before which is not the case.

生成的(修剪并重命名的)SQL是:

The generated (trimmed & renamed) SQL is:

NHibernate: select child0_.ID as child1_1_, child0_.NAME as NAME1_, child0_.PARENT_ID as COMMAND7_1_, from CHILD child0_
NHibernate: select parent0_.PARENT_ID as parent1_10_
NHibernate: select parent0_.PARENT_ID as parent1_10_, parent0_.NAME as parent2_10_ from PARENT parent0_
NHibernate: UPDATE CHILD SET PARENT_ID = @p0 WHERE CHILD_ID = @p1;@p0 = 2, @p1 = 1

映射文件:

<class name="MyNamespace.Child" table="CHILD">
  <id name="ID" column="CHILD_ID" type="System.Int64">
    <generator class="assigned"></generator>
  </id>
  <property name="Name" column="NAME"></property>
</class>

<class name="MyNamespace.Parent" table="PARENT">
  <id name="ID" column="PARENT_ID" type="System.Int64">
    <generator class="native"></generator>
  </id>
  <property name="Name" column="NAME"></property>
  <bag name="Children">
    <key column="PARENT_ID"></key>
    <one-to-many class="MyNamespace.Child"></one-to-many>
  </bag>
</class>

在搜索google时,我发现了有关版本标记的信息,这可能是一种解决方案,但我没有一个永久字段可以用作版本.在这种情况下,如何保存(插入)分配了ID的孩子及其父母?

While searching google, I found about version tag which may be a solution but I do not have a persistent field to use as version. In this case, how can I save (insert) a child with assigned id and its parent?

推荐答案

从父级层叠到子级时,NHibernate使用SaveOrUpdate方法.您是正确的,NHibernate需要某种方式来确定它应该执行插入还是更新.它将在三个不同的字段中查找一个未保存的值,以确定该实体是否为新实体.

When cascading from a parent to a child, NHibernate uses the SaveOrUpdate method. You are correct that NHibernate need some way to determine whether it should perform an insert or an update. It will look at three different fields for an unsaved value to determine if the entity is new.

  1. 编号
  2. 版本
  3. 时间戳

使用已分配的ID,您将需要版本"或时间戳记"字段,以表明该实体是新实体.

With an assigned Id, you will need either a Version or Timestamp field in order to indicate that the entity is new.

另一种方法是显式调用子项上的Save().

An alternative would be to call Save() on the children explicitly.

这篇关于如何在nhibernate中保存分配了ID的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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