ObjectContext.AcceptAllChanges! Who is accepting and who is making the changes?
I am confused by the Entity Framework ObjectContext.AcceptAllChanges. The question is, Who is accepting and who is making the changes?
In general, how to control transactions and transaction isolation in Entity Framework?
I am a new user, so I can only edit my own question .......
Thank you guys ... Akram Shahda and Ladislav Mrnka
Now my impression with EF is not very bad anymore, although it adds no value functionality wise compared with the good-old-days "Connection, Transaction, ADO.Net, Stored procedure" style database access, except may be adding some potential security problems and add some administrative works to the DBAs (as the connection string needs to have the permission to all the tables) and limit the use of some performance improvement techniques particularly during some batch database oper开发者_如何转开发ations.
I am happy that I can still retain the same level of control on transactions and transaction isolation level by "Enlist" (another Microsoft new word, why do not they just use "use") my managing my own connection and "TransactionScope" where I can choose my desired isolation level.
Now, my question about the "ObjectContext.AcceptAllChanges" are:
- Who is making the changes?
- Who is accepting the changes?
Thanks ......
By default AcceptAllChanges
is called during SaveChanges
. If saving succeeds changes are accepted. You can turn this off and accept changes manually by calling AcceptAllChanges
. This can be useful in some more advanced scenarios. One of such scenarios can be complex transaction where multiple transactional resources are handled.
For example let's assume that I want to save data to database and send message to MSMQ in the same distributed transaction:
using (var scope = new TransactionScope())
{
// This version will not accept changes automatically
context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
// Let's assume this sends message to the message queue
myMessageSender.SendSomeMessage(...);
scope.Complete();
// Now I know that transaction is completed and I can accept
// changes in the context
context.AcceptAllChanges();
}
If I didn't use manual accepting in the example the error in sending message would rolled back the transaction (so data would not be persisted to the database) but my context would be in state where all changes are accepted and I would not be able to process them again.
For transaction management in the entity framework you can refer to the following link:
http://msdn.microsoft.com/en-us/library/bb896325.aspx
精彩评论