Problem when changing entity with E.F and Dapper [closed]

1

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?

    
asked by anonymous 22.03.2018 / 12:50

1 answer

1

Your problem is that the Dapper query is outside the context of EF, so you can not modify the entity.

The error occurred because when trying to set the state of the entity as Modiffied in the EF Context, because the entity comes from Dapper, EF wants to add its entity to the database. So because the ID already exists, EF returns you this error presented in your question.

I see you have two outputs.

  • Change your query to EF by using link, basically like this.

    SeuContexto.Set(Fatura).Where(sua consulta aqui);

  • So all the entities returned in this query will be in the EF context, so you can apply CRUD without difficulty.

  • If you have to keep your Dapper query, every time you need to modify this entity, you should query the ID in EF for this entity to be in context.
  • 22.03.2018 / 14:02