Aspnet Core API with Entityframework Core - Disconnected Entiades

Asked

Viewed 131 times

3

My scenario is the following: I have an Aspnet core API that uses Entityframework for data access (postgree database).

When I receive content in Json by the API (Put) and need to update the template received in the database I have problem with related entities.

Note the following Json received from the template Request:

{
   "pedidoNumero": 0,
   "pessoaId": 5,
   "pessoa"{
       "id": 5,
       "nome": "Teste",
       "cidadeId: 1,
       "cidade": {
            "id": 1,
            "nome": "Cidade teste",
        },
   },
   pedidoItens:[
       {
           "produtoId": 1,
           "quantidade" 5,
           "total": 10.00,
       },
       {
           "produtoId": 1,
           "quantidade" 5,
           "total": 10.00,
       }]
}

I seek the Request for Id and make the call to Entity update as follows:

var pedidoExistente = _context.Pedido.Find(pedidoAtualizado.Id);
_context.Entry(pedidoExistente).CurrentValues.SetValues(pedidoAtualizado);

The problem in this scenario is that the Entity tries to insert the Person and the City related to Person

I could manipulate the object manually by giving a Attach in Person and in City, however my goal is to make the update procedure work in a generic way, so the model to be updated can have several and/or no related entity.

My intention is to: Update the request so that the Entity already recognizes existing related entities and does not update.

Is there any way or solution to the question?

Ps. The codes I posted above were made for example, it is not the actual form I use.

  • 1

    You should observe the mapping of your context, so that it is possible to change only one of the tables: example: var pedidExistent = _mapper.Map<Pedidoviewmodel>(await _pedidoRepository.Obtenporid(id id));

  • 1

    it is likely that _context.Pedido.Find is mapping more tables

  • Yes, the context is mapped to several tables, where some should be updated along with the "father" and others are only related tables that cannot be updated (case of the person). My intention is to find a Partner and or an existing EF solution.

1 answer

1

...Currentvalues.Setvalues can take any Object and maps Property values to the Attached Entity based on the Property name. If the Property Names in your model are Different from the Names in the Entity you can’t use this method and must assign the values one by one.

Using this form of update with CurrentValues.SetValues you need to have your properties mapped with the same names, so it is possible to update the models of Person and City as commented.

Here’s an answer that might be useful in this case

  • Namesake, I appreciate the answer. I already do the same thing from the reply of the article you gave me. Apparently there is no magic. The whole process must be performed manually even.

Browser other questions tagged

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