Saving in essence

I read this article and still misunderstand the key points. We don't need a call

_context.SaveChanges() 

in each operation Delete / Update / ...?

If I change the property of any entity, SaveChanges() sends the result to the database or should I manually set EntityState.Modifyed ?

Here is my code:

 public class Repository<T> : IRepository<T> where T : class { private IDbContext _context; public Repository(IDbContext context) { _context = context; } private IDbSet<T> DbSet { get { return _context.Set<T>(); } } #region IRepository<T> Members public void Insert(T entity) { DbSet.Add(entity); } public void Delete(T entity) { DbSet.Remove(entity); } public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate) { return DbSet.Where(predicate); } public IQueryable<T> GetAll() { return DbSet; } public T GetById(int id) { return DbSet.Find(id); } #endregion } public interface IDbContext { IDbSet<T> Set<T>() where T : class; int SaveChanges(); void Dispose(); } 
+8
c # entity-framework savechanges
source share
2 answers

You are asking:

We do not need a call to _context.SaveChanges () in every Delete / Update / ... operation?

No, we do not. When calling Delete we do not arbitrarily delete the object - we put it to delete.

The same thing with Update , although you do not need to do anything else that makes changes to the object. All properties (created by default template) will implement INotifyPropertyChanged so that it knows when the object was changed.

All objects (in the database at first - auto-generated by the defullt template) have the State property. This property is supported by the ObjectContext if moves occur within the scope of the ObjectEntity.

eg.

 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 State will be Detacth Console.WriteLine(c.State); 

Then you call SaveChanges all entites that have the state Added Deleted or Modified will have their changes in the database in the local transaction

EDIT

If the object is marked for deletion and you try to change it, you will get an InvalidOperationException

+4
source share

You can make many changes to your memory context, such as inserts, updates, and deletes. After calling SaveCahnges (), all the changes you made will be saved to the database in one transaction. This means that they are all filed, or none of them in the event of an error.

+2
source share

All Articles