Reputation: 11903
Let's say I have a class named Parent, in my hbm.xml there is a one-to-many set of the Child class. I want to delete all children of a given parent as efficiently as possible. This is what I'm doing now:
foreach (var child in parent1.Children)
session.Delete(child);
parent1.Children.Clear();
This results in 3+ different SQL statements: a SELECT that fetches the children entities, followed by an UPDATE that sets the foreign key in all children to NULL based on the parent foreign key, followed by multiple DELETE statements, one by one.
What I would like to see is one DELETE that deletes all children, based on their parent foreign key. Is there an NHibernate way to do that? Or do I need to bite the bullet and issue a raw SQL statement?
Upvotes: 2
Views: 703
Reputation: 123861
NHibernate introduced a very cool feature: 13.3. DML-style operations.
This supports two NHibernate/SQL features at one:
Adjust example from documentation mentioned above:
ISession session = sessionFactory.OpenSession();
ITransaction tx = session.BeginTransaction();
String hqlDelete = "delete Children c where c.ParentId = :parentId";
int deletedEntities = s.CreateQuery( hqlDelete )
.SetString( "parentId", parentId )
.ExecuteUpdate();
tx.Commit();
session.Close();
Nice reading: Ayende: NHibernate – Executable DML
Upvotes: 3