删除NHibernate中的实体时自动删除关联

删除NHibernate中的实体时自动删除关联,nhibernate,many-to-many,Nhibernate,Many To Many,我拥有以下实体: 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> Less

我拥有以下实体:

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>();
    }
  }
}
名称空间列表{
公共课{
公共虚拟整数Id{get;set;}
公共虚拟字符串标题{get;set;}
}
公共类模块{
公共虚拟整数Id{get;set;}
公共虚拟IList课程{get;set;}
公共模块(){
课程=新列表();
}
}
}
以及以下映射:

<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自动更新
模块中的关联。Lessons
以从集合中删除条目?或者我是被迫通过所有模块,寻找教训,并手动删除


编辑:修复了映射到
IList
ICollection
中的
ICollection和
,就像我想要的那样,并对其进行了测试。

结果表明,如果我们不需要IList语义,并且可以使用ICollection,则可以通过将引用从课程添加回模块来解决更新问题,例如:

public class Lesson {
  ...
  protected virtual ICollection<Module> InModules { get; set; }
  ...
}
公共课{
...
模块{get;set;}中受保护的虚拟ICollection
...
}
并在映射文件中添加:

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

...

然后,还将自动从
模块中的集合中删除
课程
。这也适用于列表,但列表索引未正确更新,导致列表中出现“漏洞”。

您的想法是错误的。如果要从
模块
中删除课程对象,请手动执行此操作。NHibernate只跟踪这样的操作,当调用
session.Commit()
时,数据库中删除
模块
课程
之间的引用

调用
session.Delete(lesson)
从数据库中删除课程对象(如果外键设置正确,则
模块
课程
之间的引用当然会被删除,但NHibernate对此不负责任)


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

好吧,所以欺骗我的是,实际上是数据库清除了引用(通过FK),而不是NHibernate?这似乎是对我所看到的行为的合理解释。