Issues updating related objects using Entity Framework and ASP net core 3
Hello friends, I hope everyone is OK! I am trying to update two entities using Entity Framework core 3.0. The parent entity "PedidoVM" which has a list of child entities "itensPedidoVM" and I would like to remove the dependency of the child objects when they are removed in the front-end and/insert a new child object. I wonder what is the best way to do this?
I am currently receiving the object of front-end in json form,
"idCliente":"1f2d8bdc-dd2c-4a41-ba3e-54213fe19c0d",
"itensPedidoVM":[ // preciso adicionar e remover itens dessa lista
{// item existente
"quantidade":1,
"preco":20.00,
"subTotal":20.00,
"idProduto":"550e9837-f574-47ae-aa9c-d06d4e1d2f85",
"idPedido":"596094e7-aa8a-4298-b560-af13a8d9270f",
"id":"1d762af7-e8aa-4303-baf0-45e3d5d47d7b"
},
// { item removido
// "quantidade":1,
// "preco":703.78,
//"subTotal":703.78,
//"idProduto":"65ee979a-00a6-4acf-adb7-9f934be43ee5",
//"idPedido":"596094e7-aa8a-4298-b560-af13a8d9270f",
//"id":"875be370-de86-421e-bbe1-db2ca3754b78"
//},
{// item novo adicionado
"quantidade":3,
"preco":2052.00,
"subTotal":6156.00,
"idProduto":"0104f083-dd99-4fac-970a-6f087554a8ae",
"idPedido":596094e7-aa8a-4298-b560-af13a8d9270f,
"id":null
}
],
"valorTotal":13101.28,
"dataVenda":"2020-03-23T13:15:17.586685",
"id":"596094e7-aa8a-4298-b560-af13a8d9270f"
}````
Quando eu tento mandar o objeto completo para que o "EF core" faça o serviço, ele não atualiza os objetos filhos que foram removidos, e não insere um objeto novo, para isso eu tive que criar duas listas uma com dados do banco de dados e outra com dados vindos do front-end, percorrer as duas listas e fazer as comparações de forma manual e executar seus devidos *inserts* e *updates*. Gostaria de saber uma forma mais elegante e mais simples de se fazer isso.
1 answers
On the front-end you keep the list of child objects updated plus the list of children already saved in the bank ( that is, the child objects obtained from the bank will have non-null id or id greater than zero, and each child object has an attribute called id, if it is a new child, instantiate the child with id = null or id = 0, and on the back-end, in your service layer you check as a pseudo code snippet below:
InserirItensPedidoVM(List<ItemPedidoVMDto> itensPedidoVMDto){
// Primeiro remove todos os ItemsPedido que não estão na lista advinda do front-end
// e que pertença somente ao pedidoId referenciado nos filhos.
this.context.Set<ItemPedidoVM>()
.RemoveAll(item => !itensPedidoVMDto.Any(item.Id) &&
itensPedidoVMDto.Any(item.PedidoId)
);
// Aqui você iria fazer o insert da nova lista
}