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);
//}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With