Save and update entities

2

public void InsertOrUpdate(T entity)
{
     if (entity.Id == 0)
     {
         context.Set<T>().Add(entity);
     }
     else
     {
        var query = context.Set<T>().Find(entity.Id);
        context.Entry(query).CurrentValues.SetValues(Entity);
     }
     //context.Entry(entity).State = entity.Id == 0 ? 
     //                     EntityState.Added : EntityState.Modified;
     context.SaveChanges();
}

I have already researched the internet and found something more performative or Clean, if someone can help me with some library thank you right away.

    
asked by anonymous 01.02.2017 / 15:57

1 answer

3

Have this here :

db.Set<Entidade>().AddOrUpdate(meuObjeto);

Accepts, in fact, several objects:

db.Set<Entidade>().AddOrUpdate(meuObjeto1, meuObjeto2, meuObjeto3);
    
01.02.2017 / 16:13