0

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.

Иван Грозный
  • 9,331
  • 12
  • 49
  • 84

1 Answers1

3

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 Single extension 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 public access.

  • A custom data class must not be sealed

  • A 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 CreateObject method to be used to create a proxy for the POCO entity. Calling the CreateObject method 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 IEntityWithChangeTracker or IEntityWithRelationships interfaces because the proxy classes implement these interfaces.

  • The ProxyCreationEnabled option 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 virtual get 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 CreateObject method on the ObjectContext when creating a new object, instead of the new operator.

Community
  • 1
  • 1
octavioccl
  • 35,665
  • 6
  • 76
  • 95