简体   繁体   中英

Saving to database taking too much time

I have to insert some record in database but it is taking too much time around 20-25 seconds. I have two methods first contains a foreach loop with list type parameter and second method has some Linq query to save and delete some record. The code is given below.

 public void InsertAssignment(List<TIVGroupItem> Item)
        {
            using (var tr = session.BeginTransaction())
            {
                try
                {
                    foreach (var item in Item)
                    {
                        ak_tIVGroupItemSelector_Insert(item);
                    }                
                    tr.Commit();
                }
                catch (Exception ex)
                {
                    tr.Rollback();
                    CusException cex = new CusException(ex);
                    cex.Write();
                }
            }

        }

second method

 public void ak_tIVGroupItemSelector_Insert(TIVGroupItem GroupItem)
        {
            try
            {
                var result = (from i in session.Query<TIVGroupItem>()
                              where i.Id == GroupItem.Id
                              select i).SingleOrDefault();
                if (result != null)
                    session.Delete(result);
                session.Save(GroupItem);
            }
            catch (Exception ex)
            { CusException cex = new CusException(ex);
                    cex.Write();
            }
        }

Item list contains some records. So how can I improve my performance with this type of problem. Is there any way to increase my performance to save the record in database?

With default NHibernate settings, every time you query NHibernate will check if the session contains any changes that might affect the outcome of the query. So as the number of objects active in the session grows, if you do repeated querying, performance will drop.

Avoid doing queries in a loop. It's better to query for multiple objects earlier.

Furthermore, you appear to be loading an object by primary key, for which you should use session.Get(id) instead. It is much faster, since it will bypass the dirty-checking mentioned above, and also look in the session's first-level cache first.

But like others said, you appear to be deleting and object and then immediately putting it back - ie it should normally be an update instead of delete+insert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM