0

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 Answer 1

3

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();
    }
}
2
  • 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.Player I 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
    Oct 18, 2009 at 1:14
  • 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
    Oct 18, 2009 at 1:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.