MK88
MK88

Reputation: 47

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();
            }

Upvotes: 0

Views: 44

Answers (1)

Julian
Julian

Reputation: 39

  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.

Upvotes: 1

Related Questions