My case is the following, I have a class orders that a client has, I have two cases, I can pass a post with a new client or I can pass a post with an existing client, if the client does not exist it will try to insert, but if there is going to throw me key error.
My controller method
[HttpPost]
public IActionResult Create([FromBody]PedidoDto pedidoDto)
{
// map dto to entity
var pedido = _mapper.Map<Pedido>(pedidoDto);
try
{
// save
_pedidoService.Create(pedido);
return Ok();
}
catch (AppException ex)
{
// return error message if there was an exception
return BadRequest(ex.Message);
}
}
My method in the order service
public Pedido Create(Pedido pedido)
{
_context.Pedidos.Add(pedido);
_context.SaveChanges();
return pedido;
}
My requested and client entities
public class Pedido
{
[Key]
public int IdPedido { get; set; }
public DateTime Fecha { get; set; }
public Cliente Cliente { get; set; }
public Domicilio Domicilio { get; set; }
public Pago Pago { get; set; }
}
public class Cliente
{
[Key]
public int IdCliente { get; set; }
public string Nombre { get; set; }
public string Apellido { get; set; }
public int DNI { get; set; }
public ICollection<Domicilio> Domicilios { get; set; }
public ICollection<Telefono> Telefonos { get; set; }
}
And the request
{
"fecha": "2017-02-01T11:50:00",
"cliente": {
"idCliente": 1,
"nombre": "Franco",
"apellido": "Pachue",
"dni": 365461,
"domicilios": null,
"telefonos": null
},
"domicilio": null,
"pago": null
}
My question would be how could I validate if the client exists and avoid the insert of the EF