简体   繁体   English

为什么Entity Framework在使用存储库模式时不跟踪更改?

[英]Why does Entity Framework not track changes when using repository pattern?

I'm using repository pattern, and my update method looks like this: 我正在使用存储库模式,我的更新方法如下所示:

    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = dataContext.GetEntry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {
            dbSet.Attach(entity);
        }

        string d1 = dbEntityEntry.CurrentValues.GetValue<string>("Description");
        string d2 = dbEntityEntry.OriginalValues.GetValue<string>("Description");

        bool b = d1 == d2;

        dbEntityEntry.State = EntityState.Modified;
    }

I am first getting the entity, then do the changes on the properties, and then update the entity. 我首先获取实体,然后对属性进行更改,然后更新实体。 The entry's state is never Detached in this situation, so Attach() is never called. 在这种情况下,条目的状态永远不会被Detached ,因此从不调用Attach()

If I change the Description property, I can see the original and current values are different. 如果我更改Description属性,我可以看到原始值和当前值不同。 If the property remains the same, both original and current values are the same. 如果属性保持不变,则原始值和当前值都相同。

GetEntry is just a wrapper method in my DBContext: GetEntry只是我的DBContext中的包装器方法:

public DbEntityEntry GetEntry(object entity)
{
    return base.Entry(entity);
}

My controller action looks like this: 我的控制器动作如下所示:

    public IHttpActionResult Update(int id, CustomerTypeDTO customerTypeDto)
    {
        var entity = customerTypeService.Get(id);

        entity.Number = customerTypeDto.Number;
        entity.Description = customerTypeDto.Description;

        entity = customerTypeService.Save(entity);

        return Ok<CustomerTypeDTO >(Mapper.Map<CustomerTypeDTO >(entity));
    }

However, EF sends a SQL statement with all the entity's fields for updating, irrelevant if they were changed or not. 但是,EF发送一个SQL语句,其中包含所有实体的更新字段,如果它们已更改则无关紧要。

Why is EF behaving like this? 为什么EF表现得像这样?

With this line: 有了这条线:

dbEntityEntry.State = EntityState.Modified;

You are telling entity framework that the entity has been modified. 您告诉实体框架该实体已被修改。 Irrespective of whether it actually has been modified. 无论它是否真的被修改过。

Therefore EF sends a SQL statement with all the entity's fields for updating. 因此,EF发送一个SQL语句,其中包含所有实体的字段以进行更新。

All you need is this : 你需要的只是这个:

    public virtual void Update(T entity)
    {
        DbSet.Attach(entity);
        DbSetFactory.ChangeEntityState(entity, EntityState.Modified);
    }

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

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