Save and update entities

Asked

Viewed 65 times

2

or personal I am trying to give an improved in my generic method that adds and updates, follows the code:

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 done a good search on the internet and I haven’t found anything more performatic or more Clean, if anyone can help me with some library I thank you from now on.

  • Is it working? Is there a problem, or is it really how the code is written that bothers you?

1 answer

3


Got this right here:

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

Accepts, incidentally, several objects:

db.Set<Entidade>().AddOrUpdate(meuObjeto1, meuObjeto2, meuObjeto3);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.