QuestionController

Let's start with QuestionController. Here's the code that will put it back on track (new/updated lines are highlighted):

using System;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using TestMakerFreeWebApp.ViewModels;
using System.Collections.Generic;
using System.Linq;
using TestMakerFreeWebApp.Data;
using Mapster;

namespace TestMakerFreeWebApp.Controllers
{
[Route("api/[controller]")]
public class QuestionController : Controller
{
#region Private Fields
private ApplicationDbContext DbContext;
#endregion

#region Constructor
public QuestionController(ApplicationDbContext context)
{
// Instantiate the ApplicationDbContext through DI
DbContext = context;
}
#endregion

#region RESTful conventions methods
/// <summary>
/// Retrieves the Question with the given {id}
/// </summary>
/// <param name="id">The ID of an existing Question</param>
/// <returns>the Question with the given {id}</returns>
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var question = DbContext.Questions.Where(i => i.Id == id)
.FirstOrDefault();

// handle requests asking for non-existing questions
if (question == null)
{
return NotFound(new
{
Error = String.Format("Question ID {0} has not been
found", id)

});
}

return new JsonResult(
question.Adapt<QuestionViewModel>(),
new JsonSerializerSettings()
{
Formatting = Formatting.Indented
});
}

/// <summary>
/// Adds a new Question to the Database
/// </summary>
/// <param name="model">The QuestionViewModel containing the
data to insert</param>
[HttpPut]
public IActionResult Put([FromBody]QuestionViewModel model)
{
// return a generic HTTP Status 500 (Server Error)
// if the client payload is invalid.
if (model == null) return new StatusCodeResult(500);

// map the ViewModel to the Model
var question = model.Adapt<Question>();

// override those properties
// that should be set from the server-side only
question.QuizId = model.QuizId;
question.Text = model.Text;
question.Notes = model.Notes;

// properties set from server-side
question.CreatedDate = DateTime.Now;
question.LastModifiedDate = question.CreatedDate;

// add the new question
DbContext.Questions.Add(question);
// persist the changes into the Database.
DbContext.SaveChanges();

// return the newly-created Question to the client.
return new JsonResult(question.Adapt<QuestionViewModel>(),
new JsonSerializerSettings()
{
Formatting = Formatting.Indented
});

}

/// <summary>
/// Edit the Question with the given {id}
/// </summary>
/// <param name="model">The QuestionViewModel containing the
data to update</param>
[HttpPost]
public IActionResult Post([FromBody]QuestionViewModel model)
{
// return a generic HTTP Status 500 (Server Error)
// if the client payload is invalid.
if (model == null) return new StatusCodeResult(500);

// retrieve the question to edit
var question = DbContext.Questions.Where(q => q.Id ==
model.Id).FirstOrDefault();

// handle requests asking for non-existing questions
if (question == null)
{
return NotFound(new
{
Error = String.Format("Question ID {0} has not been
found", model.Id)

});
}

// handle the update (without object-mapping)
// by manually assigning the properties
// we want to accept from the request
question.QuizId = model.QuizId;
question.Text = model.Text;
question.Notes = model.Notes;

// properties set from server-side
question.LastModifiedDate = question.CreatedDate;

// persist the changes into the Database.
DbContext.SaveChanges();

// return the updated Quiz to the client.
return new JsonResult(question.Adapt<QuestionViewModel>(),
new JsonSerializerSettings()
{
Formatting = Formatting.Indented
});

}

/// <summary>
/// Deletes the Question with the given {id} from the Database
/// </summary>
/// <param name="id">The ID of an existing Question</param>
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
// retrieve the question from the Database
var question = DbContext.Questions.Where(i => i.Id == id)
.FirstOrDefault();

// handle requests asking for non-existing questions
if (question == null)
{
return NotFound(new
{
Error = String.Format("Question ID {0} has not been
found", id)

});
}

// remove the quiz from the DbContext.
DbContext.Questions.Remove(question);
// persist the changes into the Database.
DbContext.SaveChanges();

// return an HTTP Status 200 (OK).
return new OkResult();
}
#endregion

// GET api/question/all
[HttpGet("All/{quizId}")]
public IActionResult All(int quizId)
{
var questions = DbContext.Questions
.Where(q => q.QuizId == quizId)
.ToArray();
return new JsonResult(
questions.Adapt<QuestionViewModel[]>(),
new JsonSerializerSettings()
{
Formatting = Formatting.Indented
});
}
}
}

There's nothing new here, as we stick to the same pattern that we already used for the QuizController; we retrieve an ApplicationDbContext instance through dependency injection, and we use it throughout all our methods to get, insert, update, and delete our entities. We can see the usual references to the namespaces we already know, such as our TestMakerFree.Data provider and the Mapster package library.

There are some minor differences here and there, such as the quizId property that we use to enforce our one-to-many relationship between a quiz and its questions; a good example would be the All() action method when we get to retrieve all the questions related to a given quizId.

..................Content has been hidden....................

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