简体   繁体   中英

What is better way to update data in EF Core

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM