Error trying to Edit PK and UK on ASP . NET Core

Asked

Viewed 68 times

0

I would like to know how to manipulate the Unique Keys and Primary Keys with Entity Framework. Whenever I try to edit an attribute and pass the same value it had before, it returns me an error:

"The instance of Entity type 'Unit' cannot be tracked because Another instance with the same key value for {'Idunidade'} 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."

If I try to pass nothing, the value is blank, which is also incorrect. As I should do?

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

  • But I’m trying to update the same record with the same value...

1 answer

1

The error is occurring because you are trying to update by creating a new record, with PK of an existing.

Ex, here you are creating a new UnidadeDto

Domain.DTO.Unit unidadeDTO = New Domain.DTO.Drive();

and soon after is going on to give the UPDATE, in a new record:

_oneRepository.Update(unidadeDTO);

Being that the correct way to update your unidadeDTO, should first bring the existing database data +- as follows:

var unidadeDTO = _unidadeRepository.GetUnidadeById(unidadeDto.IdUnidade);

unidadeDTO.NomeUnidade = collection["nomeUnidade"];
unidadeDTO.EnderecoUnidade = enderecoDTO;
unidadeDTO.ImagemUnidade = "/img/Recebido/Perfil/Unidade/" + nomeArquivo;

and now to move on to the UPDATE:

_oneRepository.Update(unidadeDTO);

Browser other questions tagged

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