Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16290

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.

If I change the Description property, I can see the original and current values are different. If the property remains the same, both original and current values are the same.

GetEntryis just a wrapper method in my 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.

Why is EF behaving like this?

Upvotes: 4

Views: 1547

Answers (2)

Ognyan Dimitrov
Ognyan Dimitrov

Reputation: 6251

All you need is this :

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

Upvotes: -1

Colin
Colin

Reputation: 22595

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.

Upvotes: 4

Related Questions