Prevent the Entity Framework from trying to insert if the nested resource exists

1

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

    
asked by PCH 01.02.2018 в 15:07
source

2 answers

0

Change the model

  public class Pedido
  {
    [Key]
    public int IdPedido { get; set; }
    public DateTime Fecha { get; set; }


    public int ClienteId { get; set; }
    public Cliente Cliente { get; set; }

    public Domicilio Domicilio { get; set; }
    public Pago Pago { get; set; }
    }

Now if I pass on the request the ClientId without the Client, just insert that data, instead if I do not pass ClientId and I pass the Client object, the client creates me and adds the order to the corresponding ClientId.

    
answered by 01.02.2018 в 16:40
0

Make a database get of the object you need to update. If you do not find the object, you do the create, but if you find it, you make a mapper of your data on the object that you have obtained and then you do an update.

With that you should not have problems.

    
answered by 01.02.2018 в 16:57