I have simple Parent
-Child
relationship, Parent
has many Child
objects, the relation is unidirectional:
public class Parent
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual IList<Child> Children { get; set; }
}
public class Child
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
}
Mapping for the relation sets cascade to AllDeleteOrphan
to remove Child
objects not referenced by Parent
any more:
HasMany(x => x.Children).Cascade.AllDeleteOrphan();
And now I'm clearing the list of Child
objects:
var parent = session.Get<Parent>(1);
parent.Children.Clear();
session.Update(parent);
NHibernate deletes the Child
object as expected, but it do this by sending separate DELETE query for each Child
from the collection: DELETE FROM Child WHERE Id = ...
- that can mean really LOT of queries.
Anyway, it can be easily done using single query like DELETE FROM Child WHERE ParentId = 1
. Why NHibernate is not using the parent foreign key to clear the collection? It seems that it knows everything to prepare such query (which foreign key, what value etc.)?