2010-09-08 59 views
1
删除实体时自动去除协会

我有以下实体:NHibernate的

namespace NhLists { 
    public class Lesson { 
    public virtual int Id { get; set; } 
    public virtual string Title { get; set; } 
    } 
    public class Module { 
    public virtual int Id { get; set; } 
    public virtual IList<Lesson> Lessons { get; set; } 
    public Module() { 
     Lessons = new List<Lesson>(); 
    } 
    } 
} 

而下面的映射:

<class name="Module" table="Modules"> 
    <id name="Id"> 
    <generator class="identity"/> 
    </id> 
    <list name="Lessons" table="ModuleToLesson" 
     cascade="save-update"> 
    <key column="moduleId"/> 
    <index column="position"/> 
    <many-to-many 
     column="lessonId" 
     class="NhLists.Lesson, NhLists"/> 
    </list> 
</class> 
<class name="Lesson" table="Lessons"> 
    <id name="Id"> 
    <generator class="identity"/> 
    </id> 
    <property name="Title"> 
    <column name="Title" length="16" not-null="true" /> 
    </property> 
</class> 

当我删除了教训通过session.Delete(lesson),反正是有,我可以有NHibernate会自动更新Module.Lessons中的关联从集合中删除条目?还是我被迫通过所有的模块,并寻找教训,并手动删除?

编辑:固定ICollection<set>在映射到IList<><list>像我想和测试它。

回答

2

你有错误的想法。如果您想从Module中删除课程对象,请手动完成。 NHibernate只跟踪你的行为,当session.Commit()被调用时,则在数据库中删除ModuleLesson之间的引用。

调用session.Delete(lesson)从数据库中删除课程对象(如果外键正确设置,那么当然会删除ModuleLesson之间的引用,但它不是NHibernate的责任)。

总之,通过调用session.Delete(lesson)不能从Module.Lessons列表中自动删除课程对象。 NHibernate不跟踪这样的实体引用。

+0

好的,那么欺骗我的是它实际上是清除引用(通过FK)而不是NHibernate的数据库?这似乎是我看到的行为的合理解释。 – kaa 2010-09-09 07:22:10

0

事实证明,如果我们不需要IList的语义,可以与ICollection的做更新可以解决问题通过从课程添加引用回到模块,如:

public class Lesson { 
    ... 
    protected virtual ICollection<Module> InModules { get; set; } 
    ... 
} 

而到了映射文件添加:

<class name="Lesson" table="Lessons"> 
    ... 
    <set name="InModules" table="ModuleToLesson"> 
    <key column="lessonId"/> 
    <many-to-many column="moduleId" class="NhLists.Module, NhLists"/> 
    </set> 
</class> 

然后删除了Lesson也从集合中删除Module自动。这也适用于列表,但列表索引没有正确更新并导致列表中出现“漏洞”。