SaveChanges是否实际调用DetectChanges?

Mar*_*ark 2 entity-framework entity-framework-6

我对是否context.SaveChangesDetectChanges自动打电话感到困惑。关于Entity Framework的大多数书籍和博客都表示愿意。但是我的简单代码段。好像SaveChanges不打电话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();                
}
Run Code Online (Sandbox Code Playgroud)

这不会将更改的属性保存到数据库中。

这会:

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();                
}
Run Code Online (Sandbox Code Playgroud)

非常感谢。

Raj*_*mal 5

根据Msdn参考(https://msdn.microsoft.com/en-us/data/jj556205.aspxcontext.Configuration.AutoDetectChangesEnabled = false;将停止自动更改检测的发生,因此context.SaveChanges();将不保存任何更改。

正确的方法是:

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();
Run Code Online (Sandbox Code Playgroud)

或(您的操作方式)

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();        
Run Code Online (Sandbox Code Playgroud)

要么

不要设置context.Configuration.AutoDetectChangesEnabledfalse,除非它成为性能问题。