1
public class ProcessoOsOperacaoEntity
{
public int? Id {get; set; }
public int? IdProcessoOs { get; set; }
public virtual ProcessoOsEntity ProcessoOs { get; set; }
public int? IdUsuario { get; set; }
public virtual UsuarioEntity Usuario { get; set; }
public int? IdPatrimonio { get; set; }
public virtual PatrimonioEntity Patrimonio { get; set; }
public DateTime Inicio { get; set; } = DateTime.Now;
public StatusOperacao? Status { get; set; }
public decimal? Qtde { get; set; } = 0;
public int? IdReinicio { get; set; }
public virtual ProcessoOsOperacaoEntity Reinicio { get; set; }
}
using (var rep = new DataContext())
{
var op = rep.Operacoes.Where(w => w.IdProcessoOs == _processoOs.Id &&
w.IdUsuario == _usuario.Id)
.OrderByDescending(od => od.Id)
.FirstOrDefault();
if (op != null) { if (op.Status != StatusOperacao.Pausa) { op = default; } }
var operacao = new ProcessoOsOperacaoEntity
{
IdProcessoOs = _processoOs?.Id,
ProcessoOs = _processoOs,
IdUsuario = _usuario?.Id,
Usuario = _usuario,
IdPatrimonio = _patrimonio?.Id,
Patrimonio = _patrimonio,
Inicio = DateTime.Now,
Status = StatusOperacao.Executando,
Qtde = 0
};
rep.Add(operacao);
if (op != null)
{
op.IdReinicio = operacao.Id;
op.Reinicio = operacao;
rep.Update(op);
}
rep.SaveChanges();
}
I recover a record from the bank and create a new one. Inside the old one I try to put the created record in the restart property getting the error:
The instance of entity type 'ProcessoOsOperacaoEntity' cannot be tracked
because another instance with the same key value for {'Id'} is already being tracked.
When attaching existing entities, ensure that only one entity instance with
a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging'
to see the conflicting key values.
For you to create a new entity is with
new
the way you’re doing is still connected in context you should make a simple query withAsNoTrancking()
(ReadOnly
) and give anew
in the new entity. If you need to duplicate it need to do so.– novic
Why do you want to add twice the same entity? I don’t understand
– Lucas Miranda
@Virgilionovic and @Lucas I’m not trying to duplicate the entity. I’m taking the previous one, and in this previous one I’m referencing the ID of the new one. And, there’s already one
new
– Gabriel Belgamo
You’re not doing it right, you’re giving it
default
in an annexed entity and this is not the case!– novic
Default seto (null) only if it is different from pause and it enters the code down there only if it is different from null.
– Gabriel Belgamo