I have a working Update method , which is simply changing a property value and calls SaveChanges() on db context:
public void Update(int id, string name)
{
var entity = context.Entities.Single(x => x.Id == id);
entity.Name = name;
context.SaveChanges();
}
this way changes do indeed get applied , however the EnityState remains "Unchanged". Any thoughts as to why? I am trying to avoid having to tell EF what's happening explicitly e.g. using context.Entry(entity).State = EntityState.Modified;
the problem is I am using the state in the overriden SaveChanges method:
public override int SaveChanges()
{
var context = ((IObjectContextAdapter)this).ObjectContext;
var objectStateEntries =
context.ObjectStateManager
.GetObjectStateEntries(EntityState.Added | EntityState.Modified);
...
return base.SaveChanges();
}
..when debugging, i can see that the state of my entity is Unchanged.
If you haven't disabled the change tracking of EF or proxy creation, then you shouldn't have problem with that update. EF by default tracks automatically changes when you entities meet the requirements you can find in this msdn page. If you meet those requirements and check later the type of you entity once is returned by
Singleextension method you will see that is a proxy class, not your real class. So, first check if you're meeting all those requirements that EF needs to track your changes automatically, you'll be fine with that code.For either of these proxies to be created:
A custom data class must be declared with
publicaccess.A custom data class must not be
sealedA custom data class must not be
abstract.A custom data class must have a public or protected constructor that does not have parameters. Use a protected constructor without parameters if you want the
CreateObjectmethod to be used to create a proxy for the POCO entity. Calling theCreateObjectmethod does not guarantee the creation of the proxy: the POCO class must follow the other requirements that are described in this topic.The class cannot implement the
IEntityWithChangeTrackerorIEntityWithRelationshipsinterfaces because the proxy classes implement these interfaces.ProxyCreationEnabledoption must be set to true.For change tracking proxies:
Each property that is mapped to a property of an entity type in the data model must have non-sealed, public, and
virtualget and set accessors.A navigation property that represents the "many" end of a relationship must return a type that implements
ICollection, where T is the type of the object at the other end of the relationship.If you want the proxy type to be created along with your object, use the
CreateObjectmethod on theObjectContextwhen creating a new object, instead of the new operator.