我有以下型号:
<class name="Person" table="Person" optimistic-lock="version">
<id name="Id" type="Int32" unsaved-value="0">
<generator class="native" />
</id>
<!-- plus some properties here -->
</class>
<class name="Event" table="Event" optimistic-lock="version">
<id name="Id" type="Int32" unsaved-value="0">
<generator class="native" />
</id>
<!-- plus some properties here -->
</class>
<class name="PersonEventRegistration" table="PersonEventRegistration" optimistic-lock="version">
<id name="Id" type="Int32" unsaved-value="0">
<generator class="native" />
</id>
<property name="IsComplete" type="Boolean" not-null="true" />
<property name="RegistrationDate" type="DateTime" not-null="true" />
<many-to-one name="Person" class="Person" column="PersonId" foreign-key="FK_PersonEvent_PersonId" cascade="all-delete-orphan" />
<many-to-one name="Event" class="Event" column="EventId" foreign-key="FK_PersonEvent_EventId" cascade="all-delete-orphan" />
</class>
在Person和Event中都没有指向PersonEventRegistration的属性。
当我尝试从PersonEventRegistration中删除条目时,出现以下错误:
"deleted object would be re-saved by cascade"
问题是,我没有将此对象存储在任何其他集合中 - 删除代码如下所示:
public bool UnregisterFromEvent(Person person, Event entry)
{
var registrationEntry = this.session
.CreateCriteria<PersonEventRegistration>()
.Add(Restrictions.Eq("Person", person))
.Add(Restrictions.Eq("Event", entry))
.Add(Restrictions.Eq("IsComplete", false))
.UniqueResult<PersonEventRegistration>();
bool result = false;
if (null != registrationEntry)
{
using (ITransaction tx = this.session.BeginTransaction())
{
this.session.Delete(registrationEntry);
tx.Commit();
result = true;
}
}
return result;
}
我在这里做错了什么?
答案 0 :(得分:3)
据我所知,cascade="all-delete-orphan"
属于集合映射元素,而不是many-to-one
。你没有展示你的映射的另外两部分,所以我不能肯定地说,但这可能(可能)问题。
我认为Person
应该类似于:
<!-- other properties -->
<set name="Events" inverse="true" cascade="all-delete-orphan">
<key column="Person_id" />
<one-to-many class="PersonEventRegistration" />
</set>
Event
:
<!-- similar mapping for Event -->
PersonEventRegistration
:
<!-- other properties -->
<many-to-one name="Person" class="Person" column="PersonId" foreign-key="FK_PersonEvent_PersonId" cascade="delete" <!-- or many ="all" ? --> />
实际上,上面可能是相互冲突的级联(可能就是你所拥有的)。所以,我的回答是两件事:
cascade="all-delete-orphan"
对many-to-one
无意义。答案 1 :(得分:1)
尝试在删除中取消引用人员和事件:
public bool UnregisterFromEvent(Person person, Event entry)
{
var registrationEntry = this.session
.CreateCriteria<PersonEventRegistration>()
.Add(Restrictions.Eq("Person", person))
.Add(Restrictions.Eq("Event", entry))
.Add(Restrictions.Eq("IsComplete", false))
.UniqueResult<PersonEventRegistration>();
bool result = false;
if (null != registrationEntry)
{
using (ITransaction tx = this.session.BeginTransaction())
{
registrationEntry.Person = null;
registrationEntry.Event = null;
this.session.Delete(registrationEntry);
tx.Commit();
result = true;
}
}
return result;
}
另外,我不知道你可以在对象上添加限制,我会用别名和ID写这个。
.Add(Restrictions.Eq("Person", person))
.Add(Restrictions.Eq("Event", entry))