Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the Alternate for AddorUpdate method in EF Core?

I want to achieve the ADDorUpdate() method in Generic repository using EF Core like below? Can anyone help me?

  public virtual void AddOrUpdate(T entity)
    {
        #region Argument Validation

        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }
        #endregion
         DbSet.AddOrUpdate(e => e.Id, entity);  
        this.DbContext.SaveChanges();
    }
like image 863
Naurto san Avatar asked Jun 18 '20 11:06

Naurto san


People also ask

Is EF core faster than EF6?

Entity Framework (EF) Core, Microsoft's object-to-database mapper library for . NET Framework, brings performance improvements for data updates in version 7, Microsoft claims. The performance of SaveChanges method in EF7 is up to 74% faster than in EF6, in some scenarios.

What is the difference between EF6 and EF core?

EF 6 is a stable and mature ORM while EF Core is relatively new. Microsoft rebuilt EF Core from the ground up and removed many of the internal dependencies and providers that EF 6 had (like SQLClient). In the long run, that will make EF Core much more extensible and lighter weight.

How does EF core detect changes?

By default, EF Core creates a snapshot of every entity's property values when it is first tracked by a DbContext instance. The values stored in this snapshot are then compared against the current values of the entity in order to determine which property values have changed.

What is primary key in EF core?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.


1 Answers

Simply use

context.Update(entity);

It does exactly AddOrUpdate based on value of entity PrimaryKey (0 means Add, > 0 means Update):

public virtual void AddOrUpdate(T entity)
{
    if (entity == null)
        throw new ArgumentNullException("entity");

     this.DbContext.Update(entity);  
     this.DbContext.SaveChanges();
}
like image 71
Arman Ebrahimpour Avatar answered Oct 11 '22 19:10

Arman Ebrahimpour