Get data list from database server in Get API

Step_01:

First of all, i need to create DbContext file. Then we will create Controller from where we will fetch data;

namespace RootCRUDAPI.Data
{
	public class CoffeeDbContext: DbContext
	{
		public CoffeeDbContext(DbContextOptions<CoffeeDbContext> options):base(options)
		{

		}

		public DbSet<CoffeeModel> coffeeModels { get; set; }
	}
}

Step_02:

Now we will create Controller class where we will Get data, post data, delete data & update data.

namespace RootCRUDAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CoffeeController : ControllerBase
    {

        CoffeeDbContext _dbContext;
        public CoffeeController(CoffeeDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        //:DbContext

        // GET: api/Coffee
        [HttpGet]
        public IEnumerable<CoffeeModel> Get()
        {
            var coffees = _dbContext.coffeeModels.ToList();
            return coffees;
        }

    }
}

Here, i created a controller named CoffeeController which inhereted ControllerBase class. Then created object Type of CoffeeDbContext which name _dbContext. Then wrote a [HttpGet] method which return list of coffee data. It’s type of CoffeeModel.We retrive the data using _dbContext object.

823 thoughts on “Get data list from database server in Get API