NHibernate many-to-many mapping

半城伤御伤魂 提交于 2019-12-07 16:26:35

Unless I'm reading the question incorrectly you need to delete the related ScenarioSkills before you delete a Skill or a Scenario. It's pretty straighforward, you just need a custom method to delete the relates ScenarioSkill objects before you delete the parent record.

Do you want it to delete automatically though?

You'll want to set cascade="all-delete-orphan" on Skills many-to-many linking to ScenarioSkills. Just like it sounds, it will delete the orphaned records and keep that error from popping up.

As a side note, many-to-many's should be used with care. Most many-to-manys contain other information in the relationship and are better mapped as a set of one-to-manys.

Bit late on the final reply here but this the the mapping I ended up successfully implementing.

In Scenario

<bag name="skills" access="field" schema="OSM" table="ScenarioSkill" cascade="none">
  <key column="ScenarioID"
       foreign-key="FK_ScenarioSkill_Scenario" />

  <!-- Skills can be soft-deleted (groan), so ignore them if they don't 'exist' anymore. -->
  <many-to-many column="SkillID"
                class="DomainModel.Skill, DomainModel"
                foreign-key="FK_ScenarioSkill_Skill"
                where="IsDeleted = 0"/>
</bag>

In Skill

    <!-- inverse end of scenarios -->
<bag name="scenarios" access="field" inverse="true" schema="OSM" table="ScenarioSkill" cascade="none">
  <key column="SkillID"
       foreign-key="FK_ScenarioSkill_Skill" />
  <many-to-many column="ScenarioID"
                class="Scenario"
                foreign-key="FK_ScenarioSkill_Scenario" />
</bag>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!