what is the Alternate for AddorUpdate method in EF Core?

Viewed 19239

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

If you work with composite keys you can use next method I wrote:

public static void AddOrUpdateRange<TEntity>(this DbSet<TEntity> set, IEnumerable<TEntity> entities)
            where TEntity : class
        {
            foreach (var entity in entities)
            {
                _ = !set.Any(e => e == entity) ? set.Add(entity) : set.Update(entity);
            }
        }

You can check if the entity exists. Like this:

book exists= context.Set<T>().Any(x=>x.Id==entity.Id);

Use like this.

if(exists)
context.Set<T>().Add(entity);
else
context.Set<T>().Update(entity);

Edit: Since this is a generic method, you should create a constraint on the method for this to work. For example, an abstract class.

public abstract class BaseEntity
{
public int Id {get; set; }
}

Your method should then have this constraint.

public virtual void AddOrUpdate(T entity)
 where T: BaseEntity{}

Your Entity should inherit from BaseEntity.

Related