简体   繁体   中英

EntityDbContext SaveChanges : What are the differences between these two codes?

In order to performance, exception capturing and etc., What are the differences between these two codes:

           int count = 0;
           foreach (var record in SomeDbEntityList)
            {
                count++;
                dbContext.SomeDbEntity.Add(record);
                if (count > 500)
                {
                  dbContext.SaveChanges();
                  count = 0;
                }
            }
            //LeftOver
            if (count > 0)
                dbContext.SaveChanges();

The direct code:

            foreach (var record in SomeDbEntityList)
            {
                dbContext.SomeDbEntity.Add(record);
                dbContext.SaveChanges();
            }
  1. The first code saves the new changes on the DB after 500 (or less) records are entity, so 500 updates/inserts are made to the DB on the same time.
    • Advantages : you don't go for every record in the DB.
    • Disadvantages : if any of these records have an error (issue), than none of the records will be updated.
  2. The second code saves directly to the DB.

Please take a look at Unit of Work design pattern.

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