Reputation: 354
Our schema contains a table with a composite primary key. The entity does not have any version/timestamp columns. The mapping is:
mapping.CompositeId().KeyReference(e => e.ParentEntity).KeyProperty(e => e.DTFR);
When user clicks Delete button, HTTP request is posted to the server, the server creates new NHibernate session and invokes session.Delete()
:
using (var session = SessionFactory.OpenSession())
using (var trans = session.BeginTransaction())
{
foreach (var entity in entities)
session.Delete(entity);
return trans.TryCommit();
}
But NHibernate gives a warning:
Unable to determine if {Entity} with assigned identifier {Entity} is transient or detached; querying the database. Use explicit Save() or Update() in session to prevent this.
and loads the entity from database before deletion of it.
We cannot follow recommendation from the warning and use Save()
or Update()
to delete entity.
How should we rewrite our code to avoid excessive querying of database on deletion?
Upvotes: 1
Views: 871
Reputation: 6791
I think this is because the NH session that you're using to delete the entities doesn't know about/isn't tracking them.
For deletion, there's an overload of the Delete()
method that takes an HQL query. This might be a viable, and arguably more efficient, way to do what you want?
Something like:
using (var session = SessionFactory.OpenSession())
using (var trans = session.BeginTransaction())
{
session.Delete($"FROM EntityTable WHERE Id IN ({entities.Select(e => e.Id})");
return trans.TryCommit();
}
Upvotes: 1