Saving in entity framework

11,317

Solution 1

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

Solution 2

You can perform many changes in your in-memory context, such as inserts, updates and deletes. Once you call SaveCahnges() all the changes you've made will be saved in the DB at a single transaction. This means that eiteher they are all submited, or none of them in case of an error.

Share:
11,317
NET
Author by

NET

Updated on July 26, 2022

Comments

  • NET
    NET almost 2 years

    I have read this article and still misunderstanding key moments. Don't we need call

    _context.SaveChanges()
    

    in every Delete/Update/... operations?

    If I change property of any entity does SaveChanges() submitted result to database or I must 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();
    }
    
  • NET
    NET about 11 years
    so must I implement SaveChanges method in IRepository ?
  • omer schleifer
    omer schleifer about 11 years
    I'm not sure why you would want to wrap the context with your repository class. you can work with the context directly. e.g. context.Cars.AddObject(new Car()) , etc...
  • NET
    NET about 11 years
    so i need call Repository.GetAll().SaveChanges() to submit changes.Does I can still query deleted items (marked as deleted)?
  • Jens Kloster
    Jens Kloster about 11 years
    yes you need to be able to call Savechanges. Definitely. I think you could still query an item that is marked for deletion, although i would not advice it - I don't think an entity can go from Deleted to Modified
  • Jens Kloster
    Jens Kloster about 11 years
    I updated my answer. You get an exception if you try to modify an entity that is marked for deletion.