Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NHibernate deletes referenced objects one by one, not using foreign key?

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.)?

like image 328
NOtherDev Avatar asked Nov 04 '22 17:11

NOtherDev


1 Answers

NHibernate can and will do that in certain cases.

It's all explained here.

like image 63
Diego Mijelshon Avatar answered Nov 15 '22 12:11

Diego Mijelshon