Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 314
user3233682 Avatar asked Jan 13 '19 14:01

user3233682


People also ask

Which approach should you use if you prefer to use existing database in EF?

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.

How do I update an existing record in Entity Framework?

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.


1 Answers

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!

like image 104
TanvirArjel Avatar answered Nov 15 '22 09:11

TanvirArjel