4

all! I am learning NHibernate now and I would like to know is it possible to save multiple objects to database in one operation.

For example, consider this test code

    private static void SaveTestBillNamesInSession(ISession session, params string[] names)
    {
        var bills = from name in names
                    select new Bill
                        {
                            Name = name,
                            DateRegistered = DateTime.Now,
                        };
        foreach (var bill in bills)
            session.SaveOrUpdate(bill);
    }

This loop here generates many INSERT statements which may be sub-optimal in SQL Server 2008 which allows to include multiple data rows in one INSERT statement.

Is it possible to rewrite this code to make use of this functionality - insert all the data in one operation?

Update OK, now it's really started to send everything in a single batch. Many thanks to all!

Gart
  • 2,297
  • 1
  • 28
  • 36
  • Do you mean the "insert-union thing"? Is that just syntactical sugar or does it also perform better? – Paco May 14 '10 at 11:20
  • @Paco: it performs better if it's a single query vs. many independent INSERTs. If all these INSERTs come in a single batch then it's pretty much the same thing. – Gart May 14 '10 at 13:03

1 Answers1

9

There's something close to what you want.

If you set the adonet.batch_size configuration property to anything other than 0 (the default), NHibernate will send that many statements at once to SQL Server.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • I agree with this answer, if you're not sure if it's batching the inserts or not, have a look at www.nhprof.com and use Ayende's tool to see what NHibernate is doing to the database under the covers. – Chris Conway May 14 '10 at 12:42
  • +1 Excellent answer! I have read the whole NHibernate documentation, and didn't remember this detail, but that NHibernate was not designed for batch treatments. Thanks! =) – Will Marcouiller May 14 '10 at 12:54