Thursday, June 13, 2013

Updating and Deleting in Entity Framework

Whenever I want to Update or Delete in Entity Framework I do something similar to this …

var result = _db.AccountSystems.SingleOrDefault(s => s.Id == id);
if (result != null)
{
     result.Active = false;
     _db.SaveChanges();
}

I thought EF would be smart enough to combine the select and update into one db call but I was wrong. EF hits the db twice.  First to select the object and the second to update/delete the object.

You can do this in one db call by using “Attach”, like this …

var system = new AccountSystem {Id = id};

_db.AccountSystems.Attach(system);
            
system.Name = “new Name”;

_db.SaveChanges();

The only problem is that EF only updates fields that change after the object is attached.  For example the following change will not be persisted to the database

var system = new AccountSystem {Id = id};

_db.AccountSystems.Attach(system);
            
       system.Active = false;

_db.SaveChanges();

The field system.Active was false prior to the assignment so Entity Framework does not realize a property change.  You must tell EF the field has changed by the following prior to saving changes.


       _db.Entry(system).Property(p => p.Active).IsModified = true;

No comments: