开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜