Using Database Context in a Web API controller

Now that we have the database context in place and the migration is also set up, let's update the TodosController Web API controller to use TodoContext that we created earlier. Follow these steps to do so:

  1. Open TodosController.cs.
  2. Declare the _db private variable of the TodoContext type:
private TodoContext _db; 
  1. Define constructor that takes a context argument of the TodoContext type and assign the context value to _db:
        public TodosController(TodoContext context)         {             _db = context;         } 
  1. Introduce a GET action method that returns the collection of all Todo items from the database using the _db database context:
        // GET: api/todos         [HttpGet]         public IEnumerable<Todo> Get()         {  return _db.Todos.ToList(); ...

Get Learning Angular for .NET Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.