Question

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();
}
Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top