我在这里试图解决级联更新/删除问题: - )
我有一个包含子实体集合的父实体。如果我修改分离的父对象中的子实体列表,添加,删除等 - 我没有看到更新正确级联到子集合。
映射文件:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Domain"
namespace="Domain">
<class name="Parent" table="Parent" >
<id name="Id">
<generator class="guid.comb" />
</id>
<version name="LastModified"
unsaved-value="0"
column="LastModified"
/>
<property name="Name" type="String" length="250" />
<bag name="ParentChildren" lazy="false" table="Parent_Children" cascade="all-delete-orphan" inverse="true">
<key column="ParentId" on-delete="cascade" />
<one-to-many class="ParentChildren" />
</bag>
</class>
<class name="ParentChildren" table="Parent_Children">
<id name="Id">
<generator class="guid.comb" />
</id>
<version name="LastModified"
unsaved-value="0"
column="LastModified"
/>
<many-to-one
name="Parent"
class="Parent"
column="ParentId"
lazy="false"
not-null="true"
/>
</class>
</hibernate-mapping>
测试
[Test]
public void Test()
{
Guid id;
int lastModified;
// add a child into 1st session then detach
using(ISession session = Store.Local.Get<ISessionFactory>("SessionFactory").OpenSession())
{
Console.Out.WriteLine("Selecting...");
Parent parent = (Parent) session.Get(typeof (Parent), new Guid("4bef7acb-bdae-4dd0-ba1e-9c7500f29d47"));
id = parent.Id;
lastModified = parent.LastModified + 1; // ensure the detached version used later is equal to the persisted version
Console.Out.WriteLine("Adding Child...");
Child child = (from c in session.Linq<Child>() select c).First();
parent.AddChild(child, 0m);
session.Flush();
session.Dispose(); // not needed i know
}
// attach a parent, then save with no Children
using (ISession session = Store.Local.Get<ISessionFactory>("SessionFactory").OpenSession())
{
Parent parent = new Parent("Test");
parent.Id = id;
parent.LastModified = lastModified;
session.Update(parent);
session.Flush();
}
}
我认为产品已更新为其集合中没有子项的事实 - 子项将在Parent_Child表中删除。这些问题似乎与将产品附加到新会话有关?由于级联设置为all-delete-orphan,我假设对集合的更改将传播到相关的实体/表?在这种情况下删除?
我在这里缺少什么?
C
答案 0 :(得分:2)
我一直在努力解决类似的问题。不确定我的解决方案是否适合您的问题,但尝试使用Session.Merge而不是ISession.Update。