变更跟踪如何在实体框架中工作 [英] How change tracking works in Entity Framework

查看:181
本文介绍了变更跟踪如何在实体框架中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

谢谢

推荐答案

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

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. 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.

还有一个备选方案称为动态更改跟踪,它将修改条目中的当前值,同时将值分配给您的实体的属性。动态变化跟踪具有特定的要求(像实体中的所有属性必须为 virtual ),因为它必须在运行时将类包装到动态代理。这是以往的首选方式,但由于复杂情况下的一些性能问题,目前应该使用快照变更跟踪作为默认值。

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. 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.

这篇关于变更跟踪如何在实体框架中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆