Repository Pattern

Use a Repository to separate logic that retrieves data from the business logic.

It is an abstraction between data access and business logic.

The following example is based on the project in the post Entity Framework Code-First example in MVC 4, in this blog.

Example.

1. Add an Interface. The naming convention is:

I + domain name + Repository

   For a domain called Movie it will be IMovieRepository.

public interface IMovieRepository
{
   IEnumerable<Movie> GetMovies();
}

2. Add a class that will implement the interface: MovieRepository

public class MovieRepository : IMovieRepository
{
   private MovieDBContext context = new MovieDBContext();
   public IEnumerable<Movie> GetMovies()
   {
      return context.Movies.ToList();
   }
}

3. Add a controller called MoviesController.cs

public class MoviesController : Controller
{
   private MovieRepository _movieRepository = new MovieRepository();

   public ViewResult Index()
   {
      return View(_movieRepository.GetMovies());
   }
}
Advertisements
This entry was posted in CSharp, Entity Framework, MVC, Visual Studio 2012 and tagged , , , , , . Bookmark the permalink.

One Response to Repository Pattern

  1. Pingback: Dependency Injection in MVC 4 using Ninject, Unity and StructureMap (IoCs) | pepitosolis

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s