如何改变实体框架跟踪作品 [英] How change tracking works in Entity Framework

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

问题描述

,请问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 update语句

When you load the entity from the context it keeps 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 entity 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 SQL update statement for to modify changed values in the database.

这操作称为快照更改跟踪 - EF保持抓拍的条目并更新它。还有另一种叫做动态变化的跟踪,这将在您指定的价值,你的实体的财产,同时进入修改当前值。动态变化的跟踪有特殊要求(如在实体每次你的财产必须是虚拟),因为它必须在运行时包住类动态代理。它曾经是首选的方式,但由于快照更改跟踪,目前应该是使用的默认复杂的情况,一些性能问题。

This operation is called snapshot change tracking - EF keeps snap shot in the entry and updates it. There is alternative called dynamic change tracking which will modify current value in the entry in the same time you assign the value to your entity's property. The dynamic change tracking has specific requirements (like every your property in the entity must be virtual) because it must wrap your class to dynamic proxy at runtime. It used to be 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天全站免登陆