You ask:
Don't we need call _context.SaveChanges() in every Delete/Update/... operations?
No we don't. When calling Delete
we don't accually delete the entity - we mark it for deletion.
Same thing with Update
, although you dont have to do anything other that make the changes you want to the entity. All properties (generated by the default template) will implement INotifyPropertyChanged
so it knows when a entity is modified.
All entities (in database first - autogenerated by defullt template) have a State
property. This property is maintained by the ObjectContext
as long as the chages take place within the scope of the ObjectEntity.
e.g.
Customer c;
using(var context = new MyEntityContext())
{
c = context.Customer.FirstOrDefault(); //state is now Unchanged
c.Name = "new name"; // this set the State to Modified
//context.SaveChanges(); // will persist the data to the store, and set the State back to unchaged
}
//if we look at our customer outside the scope of our context
//it's State will be Detacth
Console.WriteLine(c.State);
Then you call SaveChanges
all entites that have a state of Added
Deleted
or Modified
will have their changes persisted to the database in a local transaction
EDIT
If an entity is marked for deletion, and you try to modify it - you will get an InvalidOperationException