Search log by Cpf ASP . NET CORE 3.0

Asked

Viewed 250 times

-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();

1 answer

1


The Find (and its asynchronous version) only search for primary keys. To search for other fields, you need to use other methods.

In this case, you can use the method FirstOrDefaultAsync

await _context.Clientes.FirstOrDefaultAsync(c => x.CPF == algumCpf)
  • @Perfect link! It worked right this way...

  • I tested by POSTMAN and sent the number of the CPF on the body, so he returned the account... But when sending by URL or ANGULAR only returns Notfound. I tried to convert to Tostring, but it didn’t help either... Why does this happen?

  • @Rdamazio Difficult to answer without knowing details. Try opening another question with a [mcve]

  • I’ll do it and put the code

Browser other questions tagged

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