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.
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.