Reputation: 353
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?
Upvotes: 2
Views: 1582
Reputation: 177143
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
Upvotes: 2
Reputation: 364319
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.
Upvotes: 1
Reputation: 7273
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.
Upvotes: 1