none
SaveChanges() when there is nothing to save RRS feed

  • Question

  • Just wondering.

    I have a 'Save and Close' action in a window of my application, which calls the SaveChanges() method on my object context, and closes the window. The windows UI contains several controls databound to an entity object.

    I call SaveChanges whether any changes have actually occurred or not.

    From a performance point of view, should I only be calling SaveChanges if there are actually changes? Or is the Entity Framework clever enough to detect that anyway? It may just be me, but I'm pretty sure the button responds faster and the window closes a fraction quicker if I comment out the SaveChanges line (with no actual changes made to the controls values in either case)! But I'd rather not have to write the change detection code!

    Wednesday, December 1, 2010 9:34 PM

Answers

  • When you call SaveChanges(), entity framework checks the ObjectStateManager to figure out if there are any objects that are not up to date (this is an in-memory operation on the context). If there are no changes to be saved, no communication to the database happens (you can check it out for yourself by running a sql trace). The conclusion is that the cost of calling SaveChanges is negligible in most common situations.

    • Marked as answer by rizzlwizzl Wednesday, December 1, 2010 10:05 PM
    Wednesday, December 1, 2010 10:05 PM

All replies

  • When you call SaveChanges(), entity framework checks the ObjectStateManager to figure out if there are any objects that are not up to date (this is an in-memory operation on the context). If there are no changes to be saved, no communication to the database happens (you can check it out for yourself by running a sql trace). The conclusion is that the cost of calling SaveChanges is negligible in most common situations.

    • Marked as answer by rizzlwizzl Wednesday, December 1, 2010 10:05 PM
    Wednesday, December 1, 2010 10:05 PM
  • You are right.

    I was actually noticing a speed difference, but it was because of an erronous line of code which was in fact needlessly changing my data object and so requiring changes to be saved. At least I found it by looking into the issue!

    Having removed it, there is no noticable speed difference at all.
    Wednesday, December 1, 2010 10:07 PM
  • Its a good topic for a blog posting. When you touch a property, EF modifies the state to Modified. Imagine if you assign the same value, EF would always consider it as modified so you have to be careful not to modify the value to the same value because it would cause an update.

    for instance 

    console.Writeline(customer.Name ); //prints Zee

    customer.Name = "Zee";

    console.Writeline(customer.entitystate);//will print modified.


    Zeeshan Hirani Entity Framework 4.0 Recipes by Apress
    http://weblogs.asp.net/zeeshanhirani
    Thursday, December 2, 2010 7:37 AM