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

Asked

Viewed 99 times

1

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

This is the action that receives the update form, and then calls the Salvarhistorico method:

    [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 Salvarhistorico 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 appears the error below:

System.Invalidoperationexception: 'Attaching an Entity of type 'MES.Models.Consbritadorprod' 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 yet 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.

1 answer

0


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

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

You can change the status of it to Detached and then attach in context and again switch 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 could try using the AsNoTracking in your consultation.

ConsBritadorPROD objBritador = db.Set<ConsBritadorProdHist>().AsNoTracking().First(x => x.ConsBritadorPRODId  == id);
  • 1

    Thanks I got with Detached.

Browser other questions tagged

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