我对context.SaveChanges
是否会自动调用DetectChanges
感到困惑。关于实体框架的大多数书籍和博客都表示会这样做。但我的简单代码片段。似乎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();
}
这不会将已更改的属性保存到数据库中。
这将:
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();
}
非常感谢你。
答案 0 :(得分:4)
根据Msdn参考(https://msdn.microsoft.com/en-us/data/jj556205.aspx)
context.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();
或(你是怎么做的)
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
不要将context.Configuration.AutoDetectChangesEnabled
设置为false
,除非它成为性能问题。