What is better way to update data in EF Core

.net c# entity-framework-core repository sql-update

Question

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?

1
3
1/13/2019 2:16:20 PM

Accepted Answer

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!

4
1/13/2019 2:36:35 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow