Do not update a certain EF field asp.net mvc

1

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

        [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 'Repair.Models.Conservations' 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.

If I leave without anything I get error: Converting a datetime2 data type to a datetime data type resulted in a value out of range. The statement has been terminated.

    
asked by anonymous 09.02.2018 / 21:35

1 answer

4

Once you've determined that the object was modified with EntityState.Modified you can indicate the properties you do not want to modify with 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);
    }
    
09.02.2018 / 22:32