Search code examples
c#asp.net-coregenericsentity-framework-corerepository-pattern

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();
    }

Solution

  • 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();
    }