Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework update no tracking entity

How can I update an entity that is detached from context by AsNoTracking()?

var _agency = agencyRepository.Get(filter: a => a.Id == agency.Id)
                              .AsQueryable()
                              .AsNoTracking()
                              .FirstOrDefault(); 
agencyRepository.Update(_agency);

and my Update method already set modified:

public virtual void Update(T entity)
    {            
        dbset.Attach(entity);
        dataContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
    }

Can I find the previous entity that is attached by datacontext? or any suggestion to prevent Tracking on my User entity?

like image 287
Azarsa Avatar asked Dec 28 '14 16:12

Azarsa


People also ask

How do I turn off Entity Framework tracking?

In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.

What is no tracking in Entity Framework?

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query.

How do I update my Entity Framework database?

After creating a migration file using the add-migration command, you have to update the database. Execute the Update-Database command to create or modify a database schema. Use the –verbose option to view the SQL statements being applied to the target database.


2 Answers

you can change the state of the entity:

ctx.Entry(_agency).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();

More Read this or this article.

like image 98
Mohamad Shiralizadeh Avatar answered Sep 23 '22 11:09

Mohamad Shiralizadeh


When you get your object as "AsNoTracking", it means that it's detached from the context and changes won't be tracked. All you need to do is attach it to the context again.

Here is a sample code:

async Task update_entity() {
  ctx.Attach(profile);
  profile.image_id = "12345667";
  await ctx.SaveChangesAsync();
}
like image 29
Amir.n3t Avatar answered Sep 23 '22 11:09

Amir.n3t