If it exists, update one table and insert another, if not, insert the two

2

How to make an expression using EF so that when a certain list of objects is sent and already exists in the database, it is updated and the change is inserted into another history entity, otherwise, it inserts both entities.

Example

 public void Insere(List<T> objeto)
{
  using (Context ctx = new Context())
  {

     if(objeto.Select(x => x.Id).Intersect(ctx.Entidade.Select(x => x.Id)).Any() > 0){
      //Atualizo apenas os registros existentes e insiro no histórico (Para cada item da lista)
     } 

      //Insiro os registros inexistentes e insiro no histórico (Para cada item da lista) 

}
    
asked by anonymous 23.10.2015 / 22:20

1 answer

3

This already exists. This is the AddOrUpdate extension.

Usage:

ctx.Entidade.AddOrUpdate(e => e.Id, objetos);

The first field is the field that the Entity Framework will check to see if the record exists or not. In the example, it checks by Id. If the Id does not exist, it inserts. Otherwise, update.

    
23.10.2015 / 22:28