gpt4 book ai didi

entity-framework - SaveChanges 实际上调用了 DetectChanges 吗?

转载 作者:行者123 更新时间:2023-12-04 07:22:28 25 4
gpt4 key购买 nike

我对 context.SaveChanges 是否会自动调用 DetectChanges 感到困惑。大多数有关 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();
}

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

这将:

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();
}

非常感谢。

最佳答案

根据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();

或者

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

关于entity-framework - SaveChanges 实际上调用了 DetectChanges 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com