ResultController

Last but not least, here comes the ResultController (most relevant 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 ResultController : Controller
{
#region Private Fields
private ApplicationDbContext DbContext;
#endregion

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

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

// handle requests asking for non-existing results
if (result == null)
{
return NotFound(new
{
Error = String.Format("Result ID {0} has not been
found", m.Id)

});
}

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

/// <summary>
/// Adds a new Result to the Database
/// </summary>
/// <param name="model">The ResultViewModel containing the data
to insert</param>
[HttpPut]
public IActionResult Put([FromBody]ResultViewModel 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 result = model.Adapt<Result>();

// override those properties
// that should be set from the server-side only
result.CreatedDate = DateTime.Now;
result.LastModifiedDate = result.CreatedDate;

// add the new result
DbContext.Results.Add(result);
// persist the changes into the Database.
DbContext.SaveChanges();

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

}

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

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

// handle requests asking for non-existing results
if (result == null)
{
return NotFound(new
{
Error = String.Format("Result ID {0} has not been
found", m.Id)

});
}

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

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

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

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

}

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

// handle requests asking for non-existing results
if (result == null)
{
return NotFound(new
{
Error = String.Format("Result ID {0} has not been
found", m.Id)

});
}

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

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

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

This code will definitely raise some compiler warnings due to the fact that there are no MinValue and/or MaxValue properties in the ResultViewModel class (yet); let's fill the gap by adding them both in the ResultViewModel.cs file (new lines are highlighted):

[...]

#region Properties
public int Id { get; set; }
public int QuizId { get; set; }
public string Text { get; set; }
public int? MinValue { get; set; }
public int? MaxValue { get; set; }
public string Notes { get; set; }
[DefaultValue(0)]
public int Type { get; set; }
[DefaultValue(0)]
public int Flags { get; set; }
[JsonIgnore]
public DateTime CreatedDate { get; set; }
public DateTime LastModifiedDate { get; set; }
#endregion

[...]

This will fix the warning and allow the compiler to successfully build our code. We already explained the purpose of these properties when we worked on the Result entity back in Chapter 4, Data Model with Entity Framework Core, so we won't repeat ourselves here.

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

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