简体   繁体   中英

NHibernate prevent cascade delete

Suppose I have a class Foo. I also have a view on Foo called Foo_Foo that lists a many-to-many association between Foos. I mapped this association as a simple immutable set on each Foo, with cascade="none":

<set name="association" table="Foo_Foo" cascade="none" mutable="false">
  <key column="ParentFoo" />
  <many-to-many class="Foo, MyAssembly" column="BaseFoo" />
</set>

However, when I try to delete a Foo, NHibernate tries and rightly fails to delete the Foo.association.

How can I prevent NHibernate from trying to delete the association to a view?

The collection belongs to Foo . You can't share the collection, so there is no need to keep it in the database. Cascade is used to tell NH if the referenced Foo s should be also deleted or not.

Why do you want the Foo_Foo records to keep in the database? If this should be a bidirectional many-to-many self reference, it doesn't work like this.


Edit, after understanding the question.

Cascade doesn't work in your case, because it affects only the referenced Foos.

To avoid inserts / updates and deletes of the collection table, you may try one of the following:

  • First obvious attempt is mutable="false" , which you already tried. I don't really understand why it isn't working. You may ask in the Nhibernate user group.
  • Less obvious, but promising is inverse="true" . Inverse tells NH that the collection is mapped somewhere else and doesn't need to be stored from here. So it just omits inserts, but I don't know about deletes.
  • If this doesn't work, you need to explore more complex solutions. You could map it as a one-to-many of an intermediate entity which references the Foos. The intermediate entity is a mapping to the view. It is immutable (which still may lead to delete statements). In this case, cascade="false" will work (because it is the referenced entity). It will also work configure insert, update and delete sql statements (which are empty), but this is most probably not even necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM