0
I have a layered project using DDD and am having trouble updating a record of my Personal class.
public Task Handle(UpdatePessoaSituacaoCommand message, CancellationToken cancellationToken)
{
if (!message.IsValid())
{
NotifyValidationErrors(message);
return Task.CompletedTask;
}
var pessoaSituacao = new PessoaSituacao(message.Id, message.Descricao);
var existingPessoaSituacao = _pessoaSituacaoRepository.GetById(pessoaSituacao.Id);
if (existingPessoaSituacao != null && existingPessoaSituacao.Id != pessoaSituacao.Id)
{
if (!existingPessoaSituacao.Equals(pessoaSituacao))
{
Bus.RaiseEvent(new DomainNotification(message.MessageType, "Já existe uma Situação cadastrada com o ID informado."));
return Task.CompletedTask;
}
}
_pessoaSituacaoRepository.Update(pessoaSituacao);
if (Commit())
{
Bus.RaiseEvent(new PessoaSituacaoUpdatedEvent(pessoaSituacao.Id, pessoaSituacao.Descricao));
}
return Task.CompletedTask;
}
If I comment the excerpt below, the problem does not happen, only I can not leave it commented...
var existingPessoaSituacao = _pessoaSituacaoRepository.GetById(pessoaSituacao.Id);
if (existingPessoaSituacao != null && existingPessoaSituacao.Id != pessoaSituacao.Id)
{
if (!existingPessoaSituacao.Equals(pessoaSituacao))
{
Bus.RaiseEvent(new DomainNotification(message.MessageType, "Já existe uma Situação cadastrada com o ID informado."));
return Task.CompletedTask;
}
}
But because it happens and how I can solve it?
Friend, when you search for some database record with the Entity, it is saved in a framework cache, (it is saved a reference of the object), however, when we update an object, the ID is the right one, but in the EF cache the reference is another, and this causes a conflict, because it tries to add an object with the same ID in the cache. Ideally, in the update, you first search for the ID object you want to change, and in this loaded object, you assign the changes, and then you send the update
– Gustavo Santos
The bad thing is that according to my architecture, I don’t think it would be good practice to do that... This project I did identical to Eduardo Pires, the Equinox... His works correctly, but mine doesn’t.... I don’t know why.....
– Master JR
Yes, I know the project of Eduardo, but the Entity does not help, in the real world, not everything is so beautiful, this happens also because in Equinox many things are loaded with Asnotracking, and this prevents the entities to be saved in the cache, avoiding the problem that you go through.
– Gustavo Santos
Ahhhhh then the problem was Asnotracking!!!!!!!!!!!!!!!! I added it in my Getbyid function and stopped giving error kkkkkkk Thanks @ Gustavo Santos!!!!!
– Master JR
It’s us, bro! Hahaha
– Gustavo Santos
Comments on the main post for me to define as a response?
– Master JR