views:

136

answers:

3

I need to save thousand of records in a database. I am using CastleProject ActiveRecord. The cycle which stores that amount of objects works too long.

Is it possible to run saving in a batch using ActiveRecord? What is recommended way to improve performance?

A: 

ActiveRecord (and most ORM's) are not a good fit for batch operations. With all of the change tracking going on inside an ORM, it can really slow you down.

For maximum performance, I would look to either straight ADO.NET or some kind of SQL bulk import.

Patrick Steele
ActiveRecord has various options regarding batch operations while loading. I hope they do have something for batch saving.If not, how can I couple ADO.NET batching and A.R.?
Alex
I found the link (http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/) where an approach is described to point NHibernate to use batching. However, in comments somebody mention that this does not work with SQLite (the database used in my program). It seems I should ask NHibernate guys for status of this.
Alex
A: 

It seems I found the solution. There are two main steps:

  1. Add a batching to config file: <add key="hibernate.batch_size" value="100" />
  2. Use TransactionScope around saving your objects:

using (TransactionScope scope = new TransactionScope())
{
  for (int i = 0; i < 100; i++)
  {
    Contact contact = new Contact();
    contact.Save();
  }
}
Alex
A: 

I agree with Patrick. Just wanted to mention a middle-ground solution: a stateless session. See:

Mauricio Scheffer
Thanks for your links, Mauricio. However, I think that my solution (which is below) works fine and does what I wanted. I tested this on saving 100 classes and batching improved performance 20 times!
Alex

related questions