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.
It worked just to use that line you said. Thank you. I was going crazy already haha.
– Cesar Augusto