Error trying to save data in two tables at the same time

1

Good morning. When updating a table my system has to save the current data in a historical table and only then save the form data in the table by performing the update.

This is the action that receives the form to do the update, and soon calls the method SaveHistorico:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ConsBritadorPRODId,LoginId,Data_inclusao,Hora_inclusao,Data_turno,Tempo_operacao_britador,Consumo_gipsita_britador,Consumo_gipsita_britada,Inicial_gas,Final_gas,Tempo_operacao_moinho,Producao_estuque,Turno_operacao,Observacoes")] ConsBritadorPROD consBritadorPROD)
    {
        var objlogin = db.Login.OrderByDescending(p => p.LoginId).FirstOrDefault();
        SalvarHistorico(consBritadorPROD.ConsBritadorPRODId);


        consBritadorPROD.Hora_inclusao = DateTime.Now;
        consBritadorPROD.Data_inclusao = DateTime.Today;
        consBritadorPROD.LoginId = objlogin.UsuarioId;

        if(ModelState.IsValid)
        {
            db.Entry(consBritadorPROD).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.LoginId = new SelectList(db.Login, "LoginId", "LoginId", consBritadorPROD.LoginId);
        //ViewBag.ID_Referencia = new SelectList(db.Referencias, "ID_Referencia", "ID_Referencia", consumo_britador_producao.ID_Referencia);
        return View(consBritadorPROD);
    }

The SaveHistorical method is this:

 public void SalvarHistorico(int? id)
    {
        if(id == null)
        {
            new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        try
        {
            var objlogin = db.Login.OrderByDescending(p => p.LoginId).FirstOrDefault();
            ConsBritadorPROD objBritador = db.ConsBritadorPRODs.Find(id);

            ConsBritadorProdHist histConsBritadorPROD = new ConsBritadorProdHist();

            histConsBritadorPROD.Hora_inclusao = DateTime.Now;
            histConsBritadorPROD.Data_inclusao = DateTime.Today;
            histConsBritadorPROD.LoginId = objlogin.UsuarioId;
            histConsBritadorPROD.ConsBritadorPRODId = objBritador.ConsBritadorPRODId;
            histConsBritadorPROD.Data_turno = objBritador.Data_turno;
            histConsBritadorPROD.Tempo_operacao_britador = objBritador.Tempo_operacao_britador;
            histConsBritadorPROD.Consumo_gipsita_britador = objBritador.Consumo_gipsita_britador;
            histConsBritadorPROD.Consumo_gipsita_britada = objBritador.Consumo_gipsita_britada;
            histConsBritadorPROD.Final_gas = objBritador.Final_gas;
            histConsBritadorPROD.Inicial_gas = objBritador.Inicial_gas;
            histConsBritadorPROD.Tempo_operacao_moinho = objBritador.Tempo_operacao_moinho;
            histConsBritadorPROD.Producao_estuque = objBritador.Producao_estuque;
            histConsBritadorPROD.Turno_operacao = objBritador.Turno_operacao;
            histConsBritadorPROD.Observacoes = objBritador.Observacoes;

            if(ModelState.IsValid)
            {
                db.ConsBritadorProdHist.Add(histConsBritadorPROD);
                db.SaveChanges();
            }
        }
        catch
        {
            new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

    }

However when I run the following error appears:

System.InvalidOperationException: 'Attaching an entity of type' MES.Models.ConsBriterPROD 'failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate. '

Someone could help me.

    
asked by anonymous 26.12.2017 / 14:48

1 answer

0

Certainly this is happening because its ConsBritadorPROD object is already in context, when you do Find in your SalvarHistorico method it is loading in context and mapped.

ConsBritadorPROD objBritador = db.ConsBritadorPRODs.Find(id);

You can change its state to Detached and then append to the context and switch back to Modified.

var local = db.ConsBritadorProdHist.Local.FirstOrDefault(x => x.ConsBritadorPRODId == consBritadorPROD.ConsBritadorPRODId);
if (local != null)
{
    db.Entry(local).State = EntityState.Detached;
}

db.ConsBritadorProdHist.Attach(consBritadorPROD);
db.Entry(consBritadorPROD).State = EntityState.Modified;

Or you can try to use AsNoTracking in your query.

ConsBritadorPROD objBritador = db.Set<ConsBritadorProdHist>().AsNoTracking().First(x => x.ConsBritadorPRODId  == id);
    
26.12.2017 / 16:11