tags:

views:

89

answers:

1

How can I save a collection of objects in NHibernate? I'm migration from SubSonic (I don't like SubSonic 3 version and SubSonic 2 is dead...) and this used to be a simple operation...

There is a way to map a collection(without associations) to complete this task?

My actual code is:

using (ISession session = NHibernateHelper.GetCurrentSession())
{
    using (ITransaction transaction = session.BeginTransaction())
    {
        foreach (var player in players)
        {
             session.Save(player);
             transaction.Commit();
        }
    }
}

Thanks in advance!

+1  A: 

You need to commit the transaction outside of your loop. The goal of a transaction is to essentially batch multiple operations to the database in 1 call. Here's the edited version:

using (ISession session = NHibernateHelper.GetCurrentSession())
{
    using (ITransaction transaction = session.BeginTransaction())
    {
        foreach (var player in players)
        {
            session.Save(player);
        }
        transaction.Commit();
    }
}
zowens
I already tried this, but got this exception:a different object with the same identifier value was already associated with the session: 0, of entity: TabelaDigitalCL.PlayerI solve this using a session.Flush() after every save(player)...But I think doing a Flush every time don't seems right (not performatic).Any tip?Thanks for the attention.
Juliano
Solved. I set the id of the object, even when the related table's id is set as auto-increment.This would throw a exception ins SubSonic, but works just fine for NHibernate.But thanks anyway zowens.
Juliano