简体   繁体   English

变更追踪如何在Entity Framework中运作

[英]How change tracking works in Entity Framework

Given the following code, how does EF/DbContext knows about the change made to the customer object: 给定以下代码,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 谢谢

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 SaveChanges operation 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 . 当您执行SaveChanges操作时,EF会遍历您的客户实体并更新条目中的当前值,以便它们与您实体的真实状态相匹配-此操作称为检测更改 During SQL command generation EF will compare current and original values and build an SQL update statement to modify changed values in the database. 在生成SQL命令期间,EF将比较当前值和原始值,并构建一条SQL更新语句以修改数据库中已更改的值。 This operation is called snapshot change tracking - EF keeps a snap shot in the entry. 此操作称为快照更改跟踪 -EF将快照保留在条目中。

There is an alternative called dynamic change tracking which 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. 动态更改跟踪具有特定要求(例如,实体中的所有属性都必须是virtual ),因为它必须在运行时将类包装到动态代理中。 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. 这曾经是首选方法,但是由于复杂场景中的某些性能问题,快照更改跟踪当前应该用作默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM