I am using .NET Core 2.2, EF Core and C#. I have created a web API project.
I was requested to do an Upsert (insert or update). The entities structure is:
Movie
User
Rating: this is used to give a rating to a movie, so a new rating will have the MovieId (from Movie) the UserId (from User) and the Rating value.
In the Web API controller I have this request for the result of the upsert:
404 (if movie or user is not found)
400 (if the rating is an invalid value, the values can be an integer from 1 to 5)
200 (OK)
So, according to the request, I have implemented this code, but it does not look correct according to the SOLID principles. Is there any way to refactor this an get a better code? Obviously: making one method for the update and other to create is not an option as it does not respect the request.
This is the code:
[Route("apid/movies")]
[ApiController]
public class MoviesDController : ControllerBase
{
private readonly IRatingRepository _repository;
private readonly IUserRepository _userRepository;
private readonly IMovieRepository _movieRepository;
public MoviesDController(IRatingRepository repository, IUserRepository userRepository, IMovieRepository movieRepository)
{
_repository = repository;
_userRepository = userRepository;
_movieRepository = movieRepository;
}
// POST: apid/movies
[HttpPost]
public IActionResult Upsert([FromBody] Rating rating)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//1) Get the User
var user = _userRepository.GetById(rating.UserId);
if (user == null)
{
return NotFound("User not found...");
}
//2) Get the Movie
var movie = _movieRepository.GetById(rating.MovieId);
if (movie == null)
{
return NotFound("Movie not found...");
}
//3) Get Rating
var existingRating = _repository.GetMovieRating(rating.UserId, rating.MovieId);
if (existingRating == null)
{
//Insert
_repository.InsertRating(rating);
return Ok("Rating added");
}
existingRating.RatingValue = rating.RatingValue;
//Update
_repository.UpdateRating(existingRating);
return Ok("Rating updated");
}
}
Thanks!