I'm developing a multi-tier app using EF CF . I managed to delete a detached entity this way:
public void Delete(DbSet MySet, object Obj)
{
MySet.Attach(Obj);
var Entry = this.Entry(Obj);
Entry.State = EntityState.Deleted;
this.SaveChanges();
}
This method is defined in a class I called Adapter:DbContext. The thing is, when updating, similar code doesn't work:
public void Update(DbSet MySet, object Obj)
{
MySet.Attach(Obj);
var Entry = this.Entry(Obj);
Entry.State = EntityState.Modified;
this.SaveChanges();
}
This does not update the database nor throw any exceptions How should I update a detached entity?
Instead of attaching the object, try retrieving the object and updating it - Note: I'm assuming your Id is Obj.Id
public void Update(DbSet MySet, object Obj)
{
var objToUpdate = MySet.Find(Obj.Id);
if (objToUpdate != null)
{
var Entry = this.Entry(objToUpdate );
Entry.CurrentValues.SetValues(Obj)
Entry.State = EntityState.Modified;
this.SaveChanges();
}
}