简体   繁体   中英

NHibernate - SQL Server CE - Delete Cascade not working

I have two tables:

  • Receipt
  • ReceiptJournal

Receipt has 0...n ReceiptJournals

The mapping for this (in Receipt ) looks like:

this.HasMany(x => x.ReceiptJournals).AsSet().Fetch.Select().Inverse().Cascade.Delete();

The underlying database which I use is SQL Server CE 4.0.

Now, when I execute a delete-statement

const string sql = "delete from Receipt where IsFinished = 0 and IsParked = 0";
var query = NHibernateHelper.CurrentSession.CreateSQLQuery(sql);
query.ExecuteUpdate();

I get an exception:

Could not execute native bulk manipulation query:delete from Receipt where IsFinished = 0 and IsParked = 0[SQL: delete from Receipt where IsFinished = 0 and IsParked = 0]

System.Exception {NHibernate.Exceptions.GenericADOException}

[System.Data.SqlServerCe.SqlCeException] {"Der Primärschlüsselwert kann nicht gelöscht werden, da noch Verweise auf diesen Schlüssel vorhanden sind. [ Foreign key constraint name = FK_Receipt_ReceiptJournal ]"} System.Data.SqlServerCe.SqlCeException

Does NHibernate with SQL Server CE not support cascade delete or am I doing something wrong?

You probably want Cascade.AllDeleteOrphan() . It's a timing problem, NHibernate is attempting to delete from Receipt first but can't because of the foreign key constraint. Setting the cascade strategy to AllDeleteOrphan() will cause it to delete the ReceiptJournal records first because they will be orphaned.

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