I have a Dapper query, where I search for an entity:
var fatura = ObterPorClientedEDataVencimento(cobranca.ClienteId, cobranca.DataCobranca);
The Method and properties of my entity are in this Gist
, I put it there just so the question does not get too extensive.
link
That brings the data normally. However, when I try to change this entity, I get the error:
Attaching an entity of type 'PagueLa.Gateway.Domain.Entities.Fatura' failed because another entity of the same type has already 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 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. ", "ExceptionType": "System.InvalidOperationException
From what I understood from the error, EF did not "detect" that I'm trying to make a change, even setting the entity's Status as Modified
, and tries to add it again, but Id already exists in the bank. Here's my method below for a better understanding of the problem:
cobranca.FaturaId = fatura.FaturaId;
fatura.Valor += cobranca.Valor;
_cobrancaRepository.Atualizar(cobranca);
Db.Entry(fatura).State = EntityState.Modified;
I made a test taking the% of the invoice, the query made with Dapper and I made a GetPorId with the E.F and the error does not happen.
//Isso Funciona
var fatura = ObterPorClientedEDataVencimento(cobranca.ClienteId, cobranca.DataCobranca);
if (fatura != null)
fatura = ObterPorId(fatura.FaturaId.Value);
Within that I have some questions.
Why does this happen?
How can I use E.F to work with
ID
in this scenario?What is the best way to solve this problem?