Reputation: 3806
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);
//}
}
Upvotes: 7
Views: 3050
Reputation: 37770
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.
Upvotes: 4