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?
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.
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With