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?
If you have an existing database, then you can create an EDM from an existing database in the database-first approach. If you do not have an existing database or domain classes, and you prefer to design your DB model on the visual designer, then go for the Model-first approach.
We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.
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!
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