-1
I created a simple CRUD using ASP . NET CORE 3.0 using EF. All basic CRUD operations are running normal.
I tried to create a method manually to search a record by the client’s CPF as code below, but it always returns me Notfound.
How could I make a simple method to search by CPF and return the Client object?
Below the Client code
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ClienteController : ControllerBase
{
private readonly APIDBContext _context;
public ClienteController(APIDBContext context)
{
_context = context;
}
// GET: api/Cliente
[HttpGet]
public async Task<ActionResult<IEnumerable<Cliente>>> GetClientes()
{
return await _context.Clientes.ToListAsync();
}
// GET: api/Cliente/5
[HttpGet("{id}")]
public async Task<ActionResult<Cliente>> GetCliente(int id)
{
var cliente = await _context.Clientes.FindAsync(id);
if (cliente == null)
{
return NotFound();
}
return cliente;
}
// GET: api/Cliente/search/12345678901
[HttpGet("{cpf}")]
[Route("search")]
public async Task<ActionResult<Cliente>> SearchCliente(string cpf)
{
var cliente = await _context.Clientes.FindAsync(cpf);
if (cliente == null)
{
return NotFound();
}
return cliente;
}
// PUT: api/Cliente/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCliente(int id, Cliente cliente)
{
if (id != cliente.clienteID)
{
return BadRequest();
}
_context.Entry(cliente).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClienteExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Cliente
[HttpPost]
public async Task<ActionResult<Cliente>> PostCliente(Cliente cliente)
{
_context.Clientes.Add(cliente);
await _context.SaveChangesAsync();
return CreatedAtAction("GetCliente", new { id = cliente.clienteID }, cliente);
}
// DELETE: api/Cliente/5
[HttpDelete("{id}")]
public async Task<ActionResult<Cliente>> DeleteCliente(int id)
{
var cliente = await _context.Clientes.FindAsync(id);
if (cliente == null)
{
return NotFound();
}
_context.Clientes.Remove(cliente);
await _context.SaveChangesAsync();
return cliente;
}
private bool ClienteExists(int id)
{
return _context.Clientes.Any(e => e.clienteID == id);
}
}
}
and how the
FindAsync
will know that is passing Cpf and not id? need to report this, otherwise he can not know, would need to do something like_context.Clientes.Where(c => c.CPF == cpf).Single();
– Ricardo Pontual