Reputation: 147
What is the best way to update data in EF core in asp.net core application? I can do it like this
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private DbContext context;
private DbSet<T> entities;
public Repository(DbContext context)
{
this.context = context;
this.entities = context.Set<T>();
}
public void Update(T entity)
{
T exist = this.entities.Find(entity.Id);
this.context.Entry(exist).CurrentValues.SetValues(entity);
this.context.SaveChanges();
}
}
Or i can use the Update() method of DbSet. But to use it I need to set QueryTrackingBehavior to "no-tracking" firstly, something like this:
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private DbContext context;
private DbSet<T> entities;
public Repository(DbContext context)
{
this.context = context;
this.context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
this.entities = context.Set<T>();
}
public void Update(T entity)
{
this.entities.Update(entity);
this.context.SaveChanges();
}
}
Is it a good idea? What option is better and why?
Upvotes: 7
Views: 15021
Reputation: 32109
According to EF Core documentaion
SetValues will only mark as modified the properties that have different values to those in the tracked entity. This means that when the update is sent, only those columns that have actually changed will be updated. (And if nothing has changed, then no update will be sent at all.)
So I think your first approach (this.context.Entry(exist).CurrentValues.SetValues(entity);
)
should be the best for updating entity!
Upvotes: 14