Entity framework 6 ObjectMaterialized event and SaveChanges override

966 views Asked by At

I'm using Model First approach and I have one abstract class MyEntity which have few flags with attribute [NotMapped]. All my entities inherits from MyEntity. Inside the ObjectMaterialized event handler I set those flags to indicate the entity is materialized and something that related to my application.

Inside my SaveChanges() override, I call base.SaveChanges() and then reset those flags. It seems it causes the entity update to database although there are no real data changed.

My questions are:

  1. Those flags are not mapped to database columns, why changing them caused entity update to database?

  2. I tried to place those flags into partial classes instead of the abstract class inherited by every entity. It seems those flag changes still cause entity update to database. Why is that?

  3. I also tried to set those flag properties as unchanged after I reset their values before base.SaveChanges(). Although this will not cause the database update, my application doesn't behave correctly. This approach basically plays with the entity/property State to avoid updating the database. But what side effect it may cause?

1

There are 1 answers

0
Steve Li On

Finally I resolved this by changing the entity state to EntityState.Unchanged. It works for my app. But there is still one issue about how to change the state.

The following way to change the state caused problem:

dbContext.Entry(entity.Entity).State = EntityState.Unchanged;

I have to change the state using the following code:

ObjectStateEntry state = ((IObjectContextAdapter)dbContext).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity.Entity);
state.ChangeState(EntityState.Unchanged);