1.0.2.0
Mapping documents:
Parent.hbm.xml
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="HYLQ.Core.Domain.Parent, HYLQ.Core" table="Parent">
<id name="Id" column="Id" unsaved-value="0">
<generator class="assigned" />
</id>
<property name="Title" type="String" length="200" />
<bag name="Childs" lazy="true" table="Child" inverse="true" cascade="all"
access="NHibernate.Generics.GenericAccessor, NHibernate.Generics" >
<key column="pid" />
<one-to-many class="HYLQ.Core.Domain.Child, HYLQ.Core" />
</bag>
</class>
</hibernate-mapping>
Child.hbm.xml
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="HYLQ.Core.Domain.Child, HYLQ.Core" table="Child">
<id name="Id" column="Id" unsaved-value="0">
<generator class="assigned" />
</id>
<property name="Memo" type="String" length="200" />
<many-to-one name="Parent" column="pid" class="HYLQ.Core.Domain.Parent, HYLQ.Core"
access="NHibernate.Generics.GenericAccessor, NHibernate.Generics" />
</class>
</hibernate-mapping>
測試代碼:
{
int id = 1;
Parent parent = new Parent();
parent.Id = id;
parent.Title = "tetetet";
Child child = new Child();
child.Id = 1;
child.Memo = "222";
child.parent = parent;
parent.Childs.Add(child);
ITransaction trans = session.BeginTransaction();
try
{
session.Save(parent);
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
當我設置了
chilid.Id =1的時候,則出現了
Test method TestProject1.TestCategory.AddParentChild threw exception: NHibernate.HibernateException: SQL insert, update or delete failed (expected affected row count: 1, actual affected row count: 0). Possible causes: the row was modified or deleted by another user, or a trigger is reporting misleading row count..
跟蹤執行的SQL語句後,發現並不是Insert Child,而是Update Child。
當我將chilid.Id =1註釋後,就正常,不過chilid.Id他用 unsaved-value="0"代替。
執行的SQL語句都是正常的。
而我在網上看到一些One2Many的例子中其中表的主鍵都是自增長的後非assigned的。
所以這個問題很是困惑,最後,自己寫了一個自定義的Generator來生產ID,
後來就沒有出現上述的情況了。
你們碰到過這種情況嗎?