What is the difference between the following:
db.AcceptAllChanges();
// vs
db.SaveChanges();
db.AddToCustomer()
// vs
db.Customers.AddObject(Mycustomer);
and why there is db.Customers.DeleteObject(Mycustomer);
and no db.DeleteFromCustomer(Mycustomer);
when should i use each one ?
also is entity framework threadsafe ? i mean if two threads update the object in the context sametime would it crash ?
thanks in advance
The AcceptAllChanges method is useful in the scenario where a transaction has failed and a user wants to retry. If you call SaveChanges() or SaveChanges(true),the EF simply assumes that if its work completes okay, everything is okay, so it will discard the changes it has been tracking, and wait for new changes.
SaveChanges method saves all changes made in the context of the database. You can add, modify, and remove data using your context and entity classes. SaveChanges method automatically call DetectChanges method to discover any changes to entity instances before saving to the underlying database.
SaveChanges() always returns 0 – Entity Framework According to EF documentation, SaveChanges() should return a number of affected rows.
db.AcceptAllChanges()
assumes you have finished with any associated change history and discards it - if you have any further problems you cannot recover those changes. db.SaveChanges(false)
does keep those changes in memory in case there are problems.
See http://blogs.msdn.com/b/alexj/archive/2009/01/11/savechanges-false.aspx for a more in depth answer.
db.AddToCustomer()
is a strongly typed wrapper around db.Customers.AddObject()
. Look at the definition of it and you'll see what I mean. I would use the db.AddToCustomer()
method purely as it is strongly typed and gives you compile time type checking.
I imagine the only reason why there's no DeleteFromCustomer()
is that they didn't think the work would be necessary (people tend to add more than they delete). There's nothing to stop you creating your own extension methods to implement it yourself however.
The EF is not thread safe, if you want to perform updates you'll need to manage the locking yourself. See http://blog.cincura.net/230902-multithreading-with-entity-framework/ for more :)
AcceptAllChanges
only sets all added and modified entities in ObjectContextStateManager
instance to Unchanged
state and detach all deleted entities but it didn't execute changes in database. SaveChanges
executes changes in database and by default also accept changes (can be configured not to do it).
AddToCustomer
is the same as Customers.AddObject
- it is just a shortcut (same with DeleteObject
). The first method is generated by code generator (and I think it calls the second one which is standard method of ObjectSet
).
Entity framework is not thread safe. Moreover you should be very careful when sharing ObjectContext
among several threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With