Does SaveChanges actually call DetectChanges?

entity-framework entity-framework-6

Question

I'm confusing about whether or not context.SaveChanges will call DetectChanges automatically. Most of books and blogs about Entity Framework said it would. But my simple code snippet. It seems like SaveChanges does not call DetectChanges.

using (var context = new BreakAwayContext())
{
     context.Configuration.AutoDetectChangesEnabled = false;
     var grand = context.Destinations.Single(d => d.Name == "Grand Canyon");

     grand.Description = "Changed here";
     context.SaveChanges();                
}

This will not save changed property into database.

This will:

using (var context = new BreakAwayContext())
{
     context.Configuration.AutoDetectChangesEnabled = false;
     var grand = context.Destinations.Single(d => d.Name == "Grand Canyon");

     grand.Description = "Changed here";
     context.ChangeTracker.DetectChanges();
     context.SaveChanges();                
}

Thank you so much.

1
2
11/27/2015 7:01:04 AM

Popular Answer

According Msdn reference(https://msdn.microsoft.com/en-us/data/jj556205.aspx) context.Configuration.AutoDetectChangesEnabled = false; will stop auto change detection from happening and thus context.SaveChanges(); will not save any changes.

The correct ways of doing it are:

context.Configuration.AutoDetectChangesEnabled = false;
//your changes starts
var grand = context.Destinations.Single(d => d.Name == "Grand Canyon");
grand.Description = "Changed here";
//your changes ends
context.Configuration.AutoDetectChangesEnabled = true; //enabling the auto detect
context.SaveChanges();

OR (how you did it)

context.Configuration.AutoDetectChangesEnabled = false;
//your changes starts
var grand = context.Destinations.Single(d => d.Name == "Grand Canyon");
grand.Description = "Changed here";
//your changes ends
context.ChangeTracker.DetectChanges(); // manually ask for changes detection
context.SaveChanges();        

OR

do not set context.Configuration.AutoDetectChangesEnabled to false, unless it becomes a performance issue.

5
11/27/2015 4:48:16 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow