简体   繁体   中英

Entity Framework Transaction: What is better performance-wise?

Which has better performance:

using (GADEEntities context = new GADEEntities(_connectionString))
{
   using (TransactionScope transaction = new TransactionScope())
   {
      AddToContext1(context);
      AddToContext2(context);
      AddToContext3(context);
      ...

      context.SaveChanges();

      transaction.Complete();
   }
}

or

using (GADEEntities context = new GADEEntities(_connectionString))
{
   using (TransactionScope transaction = new TransactionScope())
   {
      AddToContext1(context);
      context.SaveChanges();

      AddToContext2(context);
      context.SaveChanges();

      AddToContext3(context);
      context.SaveChanges();
      ...

      transaction.Complete();
   }
}

At any time, this could translate into 5000+ inserts into a DB on a clients machine. Is either way any different?

It's very likely that your first version will be always faster, depending on what AddToContext exactly does. If your AddToContext method adds a single or only a few new objects to the context it will be definitely much faster . Calling SaveChanges after each insert (and probably also update and delete) slows the performance extremely down.

Here are a few measurements in a similar question:

Fastest Way of Inserting in Entity Framework

The way you have it set up, I do not think there is any significant difference. The data will be transmitted either way, and that's the real bottleneck.

There is very big difference because second version is terribly wrong.

What are you doing by this code:

AddToContext1(context);
context.SaveChanges(false);

You add record to context in Added state and let the context insert the record to the database but in the same time you are saying: "Let the data in Added state".

What happesn if you call this:

AddToContext2(context);
context.SaveChanges(false);

You add another recored to context in Added state and let the context insert all records in Added state to the database = the first record will be added again

It doesn't matter if AddToContext actually performs update because it will simply do the DB command again. So if you have 5.000 records you will insert or update the first one 5.000 times!

If you want to use second version you still have to accept changes during each saving.

Btw. SaveChanges overload accepting bool is obsolete in EFv4.

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