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();
}
  1. Introduce another GET action method that removes the completed Todo items from the database and returns all the pending Todo items using the _db database context:
        // GET: api/todos/pending-only 
[HttpGet]
[Route("pending-only")]
public IEnumerable<Todo> GetPendingOnly()
{
_db.Todos.RemoveRange(_db.Todos.Where(x =>
x.Completed == true));
_db.SaveChanges();
return _db.Todos.ToList();
}
  1. Introduce a POST action method that inserts a new Todo item in the TodoContext_db database:
        // POST api/todos 
[HttpPost]
public Todo Post([FromBody]Todo value)
{
_db.Todos.Add(value);
_db.SaveChanges();
return value;
}
  1. Introduce a PUT action method that updates the existing Todo item that has the matching ID using TodoContext_db:
        // PUT api/todos/id 
[HttpPut("{id}")]
public Todo Put(int id, [FromBody]Todo value)
{
var todo = _db.Todos.FirstOrDefault(x => x.Id
== id);
todo.Title = value.Title;
todo.Completed = value.Completed;
_db.Entry(todo).State =
Microsoft.Data.Entity.EntityState.Modified;
_db.SaveChanges();
return value;
}
  1. Introduce a DELETE action method that deletes an existing Todo item that has the matching ID using TodoContext_db:
        // DELETE api/todos/id 
[HttpDelete("{id}")]
public void Delete(int id)
{
var todo = _db.Todos.FirstOrDefault(x => x.Id
== id);
_db.Entry(todo).State =
Microsoft.Data.Entity.EntityState.Deleted;
_db.SaveChanges();
}

TodosController has methods that are mapped with HTTP verbs, such as GET, POST, PUT, and DELETE. There are two GET actions: one to return all Todo items and another to return only the pending Todo items, deleting the completed Todo items. A POST action that receives a new Todo object will insert it into the database using Entity Framework. A PUT action takes two arguments: the id of the Todo item being updated and the Todo object itself. This method first fetches the matching Todo item, updates all the properties, and updates the database. Lastly, a DELETE action takes the id of the Todo item that is to be deleted; it queries the database for the matching Todo item and deletes it. The complete code snippet of TodosController is this:

[Produces("application/json")]   
[Route("api/Todos")]
public class TodosController : Controller
{
private TodoContext _db;
public TodosController(TodoContext context)
{
_db = context;
}
// GET: api/todos
[HttpGet]
public IEnumerable<Todo> Get()
{
return
_db.Todos.ToList();
}
// GET: api/todos/pending-only
[HttpGet]
[Route("pending-only")]
public IEnumerable<Todo> GetPendingOnly()
{
_db.Todos.RemoveRange(_db.Todos.Where(x =>
x.Completed == true));
_db.SaveChanges();
return _db.Todos.ToList();
}
// POST api/todos
[HttpPost]
public Todo Post([FromBody]Todo value)
{
_db.Todos.Add(value);
_db.SaveChanges();
return value;
}
// PUT api/todos/id
[HttpPut("{id}")]
public Todo Put(int id, [FromBody]Todo value)
{
var todo = _db.Todos.FirstOrDefault(x =>
x.Id == id);
todo.Title = value.Title;
todo.Completed = value.Completed;
_db.Entry(todo).State =
EntityState.Modified;
_db.SaveChanges();
return value;
}
// DELETE api/todos/id
[HttpDelete("{id}")]
public void Delete(int id)
{
var todo = _db.Todos.FirstOrDefault(x =>
x.Id == id);
_db.Entry(todo).State = EntityState.Deleted;
_db.SaveChanges();
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset