C# 实体框架中的变更跟踪如何工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10377647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:36:52  来源:igfitidea点击:

How change tracking works in Entity Framework

c#entity-framework-4dbcontextchange-tracking

提问by Yair Nevet

Given the following code, how does EF/DbContext knows about the change made to the customerobject:

给定以下代码,EF/DbContext 如何知道对客户对象所做的更改:

class Program
{
    static void Main()
    {
        using(var shopContext = new ShopContext())
        {
            var customer = shopContext.Customers.Find(7);

            customer.City = "Marion";

            customer.State = "Indiana";

            shopContext.SaveChanges();
        }
    }
}

public class ShopContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

Thank you

谢谢

采纳答案by Ladislav Mrnka

When you load the entity from the context it keeps an additional data structure - let's call it entry. The entry contains two set of values - original values and current values. When you execute the SaveChangesoperation EF goes through your customer entities and updates current values in the entry so that they match with the real state of your entity - this operation is called detecting changes. During SQL command generation EF will compare current and original values and build an SQL update statement to modify changed values in the database. This operation is called snapshot change tracking- EF keeps a snap shot in the entry.

当您从上下文加载实体时,它会保留一个额外的数据结构——我们称之为条目。该条目包含两组值 - 原始值和当前值。当您执行SaveChanges操作时,EF 会遍历您的客户实体并更新条目中的当前值,以便它们与您的实体的真实状态相匹配 - 此操作称为检测更改。在 SQL 命令生成期间,EF 将比较当前值和原始值,并构建 SQL 更新语句来修改数据库中更改的值。此操作称为快照更改跟踪- EF 在条目中保留快照。

There is an alternative called dynamic change trackingwhich will modify the current value in the entry at the same time you assign the value to your entity's property. Dynamic change tracking has specific requirements (like all of your properties in the entity must be virtual) because it must wrap your class to a dynamic proxy at runtime. This used to be the preferred way but due to some performance issues in complex scenarios, snapshot change tracking is currently supposed to be used as default.

还有一种称为动态更改跟踪的替代方法,它将在您将值分配给实体属性的同时修改条目中的当前值。动态更改跟踪具有特定要求(例如实体中的所有属性都必须是virtual),因为它必须在运行时将您的类包装到动态代理。这曾经是首选方式,但由于复杂场景中的一些性能问题,目前应该默认使用快照更改跟踪。