NHibernate One-to-Many Cascades

I have a class "Photo" and a class "Comment". A photo may contain several comments.

I have this configured as a one-to-many relationship in my HBM mapping file and set cascade = "all-delete-orphan" in the Comments bag in the Photo.hbm.xml mapping file.

However, if I try to delete a photo with 1 or more comments associated with it, I get: "DELETE operation contradicts the REFERENCE restriction" FK_Comments_Photos "

I tried a couple of other cascade options against the comment bag in my Photo.hbm.xml, but no matter what I set, I get the same result every time. I just want to delete the photo and automatically delete all related comments.

Here is my photo mapping (edited for brevity):

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" .... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Photo" table="Photos">
    <id name="PhotoId" unsaved-value="0">
        <column  name="PhotoId" />
        <generator class="native" />
    </id>
    ...
    <bag name="Comments" table="Comments" cascade="all-delete-orphan" order-by="DateTimePosted desc" where="Approved=1">
        <key column="PhotoId" />
        <one-to-many class="Comment" />
    </bag>
</class>

Here is my comment mapping (edited for brevity):

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Comment" table="Comments">
    <id name="CommentId" unsaved-value="0">
        <column name="CommentId"></column>
        <generator class="native" />
    </id>
    ...
    <property name="Author" not-null="true" />
    <property name="Body" not-null="true" />
    <property name="Approved" not-null="true" />
    <many-to-one name="Photo" not-null="true">
        <column name="PhotoId" />
    </many-to-one>
</class>

Does anyone have any suggestions as to why the cascade does not happen when I try to delete a photo with comments related to it?

: - " " SQL Server "Cascade", , , t NHibernate Mapping. - NHibernate Mapping , , , , NHibernate ?

+3
4

, - , not-null = "true". - NHibernate Photo, , , Photo, SQL Server .

:

  • null

-null = "true" "--" , .

+4

inverse="true" .

+2

1 .. .

Finally, the solution came down to the DB. I had to change the restrictions of the FK key in "INSERT UPDATE SPECIFICATIONS", "Delete Rule": from "No Actions" to "Cascade"

in addition, you can also set the "Update rule": from "No action" to "Cascade"

+1
source

You can specify the delete-cascade option in NH:

<bag name="Comments" cascade="all-delete-orphan" order-by="DateTimePosted desc" where="Approved=1">
    <key column="PhotoId" on-delete="cascade"/>
    <one-to-many class="Comment" />
</bag>

You should probably make it reverse. Then I wonder where your FK_Comments_Photos column is listed.

0
source

Source: https://habr.com/ru/post/1786865/


All Articles