NHibernate多对一级联 [英] NHibernate Many-to-one cascade
问题描述
我有以下两个课程:
public class Project
{
public virtual int ProjectId { get; set; }
public virtual string ProjectName { get; set; }
public virtual LegalEntity LegalEntity { get; set; }
}
和
public class LegalEntity
{
public virtual int LegalEntId { get; set; }
public virtual string Name { get; set; }
}
映射为:
<class name="Project" table="Project" dynamic-update="true">
<id name="ProjectId">
<generator class="native"/>
</id>
<property name="ProjectName" />
<many-to-one name="LegalEntity" column="LegalEntId" fetch="join" cascade="all-delete-orphan" />
</class>
和
<class name="LegalEntity" table="LegalEnt" dynamic-update="true">
<id name="LegalEntId">
<generator class="native"/>
</id>
<property name="Name" />
</class>
在数据库中,项目"表的FK指向LegalEntity的PK列.一个项目只有一个法人实体.不同的项目可以具有相同的法人实体.这就是我多对一的原因.不确定这是否正确.
In database, Project table has a FK to LegalEntity's PK column. One Project will have only one legal entity. Different projects can have same legal entity. So thats the reason I have gone for many-to-one. Not sure if this is correct though.
插入和更新工作正常.但是,如果我更新了项目中的法人实体ID,并且该法人实体成为孤立的,我希望将其删除.但是它没有发生.在理解所有删除孤岛上我错了吗?如果是,我如何实现此行为?
Insert and update is working fine. But if I update a legal entity id in a project and that legal entity becomes orphan, I want it to be deleted. But its not happening. Am I wrong in understanding delete-all-orphan? If yes, how can I achieve this behaviour?
推荐答案
many-to-one
级联不支持all-delete-orphan
,请参见:
The many-to-one
cascade does not support all-delete-orphan
, see:
<many-to-one
...
cascade="all|none|save-update|delete" (4)
...
此外,在NHibernate的会话中几乎不可能处理此功能.因为不必清楚,所以引用的many-to-one
确实是孤立的.数据库中应该做一些更进一步的检查...可能还有其他地方引用此表行...
Also, it would be almost impossible to handle this feature by NHibernate's session. Because it does not have to be clear, that the referenced many-to-one
is really orphan. There should be some farther checks in DB... there could be other places referencing this table row...
建议:作为DAO或Business Facade实施的一部分,在您的代码中进行.检查是否确实存在没有依赖项,然后发出明确的Delete()
Suggestion: do it in your code as a part of the DAO or Business Facade implementation. Check if there are really no dependencies, and then issue explicit Delete()
EXTEND:这是一种QueryOver
语法,用于获取所有"orphan" LegalEntity
EXTEND: Here is a QueryOver
syntax to get a list of all "orphan" LegalEntity
// subquery
var subquery = QueryOver.Of<Project>()
.Select(x => x.LegalEntity.LegalEntId);
// just these legal entities, which are NOT used
var query = session.QueryOver<LegalEntity>()
.WithSubquery
.WhereProperty(y => y.LegalEntId)
.NotIn(subquery)
;
// orphans
var list = query
.List<LegalEntity>();
这篇关于NHibernate多对一级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!