If there is update a table and insert into another, if not, insert into the two

Asked

Viewed 60 times

2

How to make an expression using EPH so that when a certain list of objects is sent and already exists in the database, it is updated and the change is inserted in another historical entity, otherwise, it inserts the two 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) 
  
}

1 answer

3


It already exists. It’s the extension AddOrUpdate.

Use:

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

The first field is the field that the Entity Framework will do to verify whether or not the record exists. In the example, it will check for Id. If Id does not exist, enter. Otherwise, update.

Browser other questions tagged

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