Searching & Filtering data in ASP.NET Core 7.0

Now i will implement searching api method. If user given text matched with database value then api will reture these array types of values.

Step_01:

namespace RootCRUDAPI.Interfaces.Manager
{
	public interface ICoffeeManager: ICommonManager<CoffeeModel>
	{
                CoffeeModel GetById(int id);
		ICollection<CoffeeModel> GetAll(string title);
		ICollection<CoffeeModel> SearchCoffee(string text);
    }
	
}

Here, first of all, i wrote GetAll interface which return ICollection. where user give there input text.

Step_02:

namespace RootCRUDAPI.Manager
{
    public class CoffeeManager : CommonManager<CoffeeModel>, ICoffeeManager
    {
        public CoffeeManager(CoffeeDbContext _dbContext) : base(new CoffeeRepository(_dbContext))
        {
        }

        public ICollection<CoffeeModel> GetAll(string title)
        {
            return Get(c => c.Title.ToLower() == title.ToLower());
        }

        public CoffeeModel GetById(int id)
        {
            return GetFirstOrDefault(c => c.Id == id);
        }

        public ICollection<CoffeeModel> SearchCoffee(string text)
        {
            return Get(c=>c.Title.ToLower().Contains(text.ToLower()) || c.Description.ToLower().Contains(text));
        }
    }
}

Here i inherited GetAll interface method & implemented functionality what i want to do. This method i got the user text and try to match with CoffeeModel title properties. If the title match with this text then this function return those values.

step_03:

         //Searching
        [HttpGet("title")]
        public IActionResult GetAll(string title)
        {
            try
            {
                var coffees = _coffeeManager.GetAll(title);
                return Ok(coffees);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

Finally i implemented GetAll searching method in my controller.

{BaseURL/api/Coffee/title?title=string}

Step_04:

if we want to get the value where match with letter. I means when user input any letter then database match with these letter model properties then return values. And also we want to match with multiple properties. This problem can be solved using below functionality:

       public ICollection<CoffeeModel> SearchCoffee(string text)
        {
            return Get(c=>c.Title.ToLower().Contains(text.ToLower()) || c.Description.ToLower().Contains(text));
        }

400 thoughts on “Searching & Filtering data in ASP.NET Core 7.0

Leave a Reply

Your email address will not be published. Required fields are marked *