Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContext.Entry performance issue

Following Julia Lermas book 'DbContext' on a N-Tier solution of keeping track of changes, I provided each entity with a State property and a OriginalValues dictionary (through IObjectWithState). After the entity is constructed I copy the original values to this dictionary. See this sample (4-23) of the book:

public BreakAwayContext()
{
  ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += (sender, args) =>
  {
      var entity = args.Entity as IObjectWithState;
      if (entity != null)
      {
        entity.State = State.Unchanged;
        entity.OriginalValues = BuildOriginalValues(this.Entry(entity).OriginalValues);
      }
    };
}

In the constructor of the BreakAwayContext (inherited from DbContext) the ObjectMaterialized event is caught. To retrieve the original values of the entity, the DbEntityEntry is retrieved from the context by the call to this.Entry(entity). This call is slowing the process down. 80% of the time of this event handler is spend on this call.

Is there a faster way to retrieve the original values or the entities DbEntityEntry?

like image 999
pexxxy Avatar asked Oct 04 '12 09:10

pexxxy


1 Answers

Context.Entry() calls DetectChanges() that depends on number of objects in context and could be very slow. In your case you could replace with faster version ((IObjectContextAdapter) ctx).ObjectContext.ObjectStateManager.GetObjectStateEntry(obj);

like image 176
Ben Avatar answered Oct 21 '22 05:10

Ben