Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling not found object in repository

I have a externall dll in which following is defined

namespace MoviesLibrary
{
    public class MovieDataSource
    {
        public MovieDataSource();

        public int Create(MovieData movie);
        public List<MovieData> GetAllData();
        public MovieData GetDataById(int id);
        public void Update(MovieData movie);
    }
}

I am calling this dll from repository to perform CRUD in my webapi application,now in my repostory i am writing GetMovieById method in which i am confused what to return if a movie is not found in repository and what is the more appropriate way to handle this in webapi?

MovieRepository

 public Movie GetMovieById(int movieId)
        {

            MovieData movieData = new MovieDataSource().GetDataById(movieId);
            if (movieData != null)
        {
            return MovieDataToMovieModel(movieData);
        }
        else
        {
            ??
        }
    }

MoviesController

/// <summary>
/// Returns a movie
/// </summary>
/// <param name="movie">movieId</param>
/// <returns>Movie</returns>
   public Movie Get(int movieId)
    {
    //try
    //{
        var movie = repository.GetMovieById(movieId);
        if (movie == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return movie;
    //}
    //catch (Exception e)
    //{
    //    if (e is HttpResponseException)
    //    throw new HttpResponseException(HttpStatusCode.NotFound);
    //}
}
like image 338
F11 Avatar asked Oct 21 '22 00:10

F11


1 Answers

Usually, you should throw an exception, if entity not found by its primary key.
Depending on use cases, you can put two methods in your repository (and external code, which works with repository):

public MovieData GetDataById(int id); // this throws an exception, if not found
public MovieData GetDataByIdOrDefault(int id); // this returns null, if not found

and call first one, if the entity must present in data source, or the second one, if entity could present in data source.

like image 138
Dennis Avatar answered Oct 26 '22 23:10

Dennis