Search code examples
c#.netnhibernate.net-6.0

NHibernate SaveOrUpdate takes ages


I have a dataset to be inserted into an mssql db using NHibernate on dotnet6 using c#. The dataset contains nearly 8k entries to be inserted or updated in the db. Code looks like this.

public void Execute<T>(IEnumerable<T> layouts)
    {
        using (Session = mSessionFactory.OpenSession())
        {
            using (var tx = Session.BeginTransaction())
            {
                foreach (T layout in layouts)
                {
                    Session.SaveOrUpdate(layout);
                }
                tx.Commit();
            }
        }
    }

(Using the build-in profiler of vs22 I can observe that each entry takes about 80ms: 8000/(1000/80)=640s/60=10min)
Calling this method with an array of layouts (the dataset) takes about 10~15minuts! I cant imagine this taking so long given the fact that there is only one referenced table connected to the main table in the database.

Am I missing something?


Solution

  • Using

    int i = 0;
                    foreach (T layout in layouts)
                    {
                        Session.SaveOrUpdate(layout);
                        i++;
                        if (i % 20 == 0)
                        {
                            Session.Flush();
                            Session.Clear();
                            i = 0;
                        }
                    }
                    tx.Commit();
    

    performance increased a lot.