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
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
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
Entity framework is not thread safe. Moreover you should be very careful when sharing
ObjectContext among several threads.