Blankman
Blankman

Reputation: 266960

How to bulk delete with nhibernate?

How can I delete items with nhibernate without first pulling all the objects in memory?

Is this possible or do I have to use raw sql?

Upvotes: 6

Views: 7592

Answers (2)

Vinicius Rocha
Vinicius Rocha

Reputation: 4223

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

Upvotes: 8

Newbie
Newbie

Reputation: 7249

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();
            }
        }

Upvotes: 11

Related Questions