Last active
August 29, 2015 14:05
-
-
Save ardalis/41d3634dd77493cb37a3 to your computer and use it in GitHub Desktop.
Strategy Pattern Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MoviesController : Controller | |
{ | |
private readonly IMovieRepository _movieRepository; | |
public MoviesController(IMovieRepository movieRepository) | |
{ | |
_movieRepository = movieRepository; | |
} | |
public MoviesController() : this(new EfMovieRepository()) | |
{} | |
// GET: /Movies/ | |
public ActionResult Index(string movieGenre, string searchString) | |
{ | |
ViewBag.movieGenre = new SelectList(_movieRepository.ListGenres()); | |
return View(_movieRepository.ListMovies(movieGenre,searchString)); | |
} | |
} | |
public interface IMovieRepository | |
{ | |
IEnumerable<string> ListGenres(); | |
IEnumerable<Movie> ListMovies(string movieGenre, string searchString); | |
} | |
public class EfMovieRepository : IMovieRepository | |
{ | |
private readonly MovieDbContext db = new MovieDbContext(); | |
public IEnumerable<string> ListGenres() | |
{ | |
var genreLst = new List<string>(); | |
var genreQry = from d in db.Movies | |
orderby d.Genre | |
select d.Genre; | |
genreLst.AddRange(genreQry.Distinct()); | |
return genreLst.AsEnumerable(); | |
} | |
public IEnumerable<Movie> ListMovies(string movieGenre, string searchString) | |
{ | |
var movies = from m in db.Movies | |
select m; | |
if (!String.IsNullOrEmpty(searchString)) | |
{ | |
movies = movies.Where(s => s.Title.Contains(searchString)); | |
} | |
if (!string.IsNullOrEmpty(movieGenre)) | |
{ | |
movies = movies.Where(x => x.Genre == movieGenre); | |
} | |
return movies.AsEnumerable(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment