Do not update a particular EF Asp.net mvc field

Asked

Viewed 555 times

1

I have a table that every time I create a new registration has the field Datacadastro, however when I want to edit I do not want to change the date that was registered and only changes the other fields. I have tried to do in a way that logic works but when will apply in the bank of error.

        [Key]
    public int ConsertoId { get; set; }


    public string Defeito { get; set; }

    public string Solucao { get; set; }


    public int MecanicoId { get; set; }

    public int ClienteId { get; set; }

    public DateTime DataCriacao { get; set; }


    [ForeignKey("MecanicoId")]
    public virtual Usuario Pessoa { get; set; }

    [ForeignKey("ClienteId")]
    public virtual Usuario Cliente { get; set; }

    public IEnumerable<SelectListItem> Clientes { get; set; }
    public IEnumerable<SelectListItem> Mecanicos { get; set; }

    public virtual ICollection<ConsertoDetalhes> ConsertoDetalhes { get; set; }

controller

    [HttpPost]
    public ActionResult Editar(Consertos conserto)
    {
        Db db = new Db();
        if (ModelState.IsValid)
        {
             //pega data ja cadastrada mas da erro
            // Consertos cons = db.Conserto.FirstOrDefault(x => x.ConsertoId == conserto.ConsertoId);
           // conserto.DataCriacao = cons.DataCriacao; 

            conserto.DataCriacao = DateTime.Now;//funciona mas cria nova data
            db.Entry(conserto).State = EntityState.Modified;
            db.SaveChanges();

            TempData["MG"] = "Tarefa atualziada com sucesso";
            return RedirectToAction("Editar");

        }
        ViewBag.ClienteId = new SelectList(db.Usuario.Where(u => u.Cliente).OrderBy(u => u.Nome), "UserId", "Nome", conserto.ConsertoId);
        ViewBag.MecanicoId = new SelectList(db.Usuario.Where(u => u.Mecanico).OrderBy(u => u.Nome), "UserId", "Nome", conserto.ConsertoId);
        //conserto.Clientes = new SelectList(db.Usuario.Where(u => u.Cliente).OrderBy(u => u.Nome), "UserId", "Nome", conserto.ConsertoId);

        return View(conserto);


    }

Error:Attaching an Entity of type 'Fix.Models.Fix' 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.

if I leave without anything I get error: The conversion of a datetime2 data type into a datetime data type resulted in a value outside the range. The instruction has been completed.

2 answers

3


After setting the object was modified with the EntityState.Modified you can indicate properties you do not want to modify with the IsModified = false, your method would look something like this:

[HttpPost]
    public ActionResult Editar(Consertos conserto)
    {
        Db db = new Db();
        if (ModelState.IsValid)
        {
            conserto.DataCriacao = DateTime.Now;//funciona mas cria nova data
            db.Entry(conserto).State = EntityState.Modified;

            //Indica qual propriedade não deve ser alterada
            db.Entry(conserto).Property(p => p.Datacadastro).IsModified = false;
            db.SaveChanges();

            TempData["MG"] = "Tarefa atualziada com sucesso";
            return RedirectToAction("Editar");

        }
        ViewBag.ClienteId = new SelectList(db.Usuario.Where(u => u.Cliente).OrderBy(u => u.Nome), "UserId", "Nome", conserto.ConsertoId);
        ViewBag.MecanicoId = new SelectList(db.Usuario.Where(u => u.Mecanico).OrderBy(u => u.Nome), "UserId", "Nome", conserto.ConsertoId);

        return View(conserto);
    }
  • It worked just to use that line you said. Thank you. I was going crazy already haha.

0

Hello. I know it has been more than two years since the question and it has even been answered correctly, but just to clarify if someone else falls here by parachute, your error occurred because in your method there were two tracked entities of the same type (Repairs).

If you added the property AsNoTracking() in consultation with it, it would be possible to make the manual assignment in the form.

As its name says, this property disables the tracking/tracking of the entity in question, making it a display-only entity.

The complete form of the consultation would be:

Consertos cons = db.Conserto.AsNoTracking().FirstOrDefault(x => x.ConsertoId == conserto.ConsertoId);

Browser other questions tagged

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