How to bulk delete with nhibernate?
How can I delete items with nhibernate without first pulling 开发者_StackOverflow中文版all the objects in memory?
Is this possible or do I have to use raw sql?
Use the ExecuteUpdate method. The code below will commit bulk deletion in batches. This works in NHibernate 2.1.0. (Not sure about previous versions)
foreach (List<int> batch in GetBatches(records, _batchSize))
{
using (ITransaction transaction = _session.BeginTransaction())
{
_session.CreateQuery(String.Format("DELETE FROM {0} WHERE Id IN (:idsList)", _domainObject.Name))
.SetParameterList("idsList", batch.ToArray())
.ExecuteUpdate();
transaction.Commit();
}
}
Starting from NHibernate 5 you can use the following syntax:
session.Query<Cat>()
.Where(c => c.BodyWeight > 20)
.Delete();
Beginning with NHibernate 5.0, Linq queries can be used for inserting, updating or deleting entities. The query defines the data to delete, update or insert, and then Delete, Update, UpdateBuilder, InsertInto and InsertBuilder queryable extension methods allow to delete it, or instruct in which way it should be updated or inserted. Those queries happen entirely inside the database, without extracting corresponding entities out of the database.
Source: http://nhibernate.info/doc/nhibernate-reference/querylinq.html#querylinq-modifying
精彩评论