Mohammad Taherian
Mohammad Taherian

Reputation: 1694

EF Core 3.1 Update Entity

I want to update my entity using EF Core. Which one of these 2 approaches is more efficient and better to use.

Context.Entry(entity).State = EntityState.Modified
Context.SaveChanges();

and the next one is

var exist = entities.Find(entity.Id);
Context.Entry(exist).CurrentValues.SetValues(entity);  
Context.SaveChanges();

both of theme do the job but which one is better?

Upvotes: 4

Views: 2505

Answers (1)

Guru Stron
Guru Stron

Reputation: 142833

It depends on your situation. First one, as far as I understand should rewrite whole entity in db. Second one can possibly make an extra request to the database if entity is not already tracked by context, but should update only fields which actually have changed. So if you have change tracking enabled and already fetched the entity into your context, and have a lot of columns (or columns which contain a lot of data and can be compared by EF) second one should be faster. In other cases - first one could.

Upvotes: 5

Related Questions