Leveraging Scaffolders to Implement Repository pattern for your project

I have shown in last couple of posts how to use

1. MVCScaffolding to scaffold your MVC 4 project with Razor View Engine,

2. Use the Migration tool to use code first approach.



I still want to show you how to use the repository pattern using the Scaffolding technique

Here is the outline of what we are doing.

  • Installing MvcScaffolding
  • Scaffold each model

On your project from the last post run the following command on your package manager console

PM> Install-Package MvcScaffolding

This will install all the necessary component for the MvcScaffolding for the project.


Now run following for each model

PM> Scaffold Repository Role

PM> Scaffold Repository user

PM> Scaffold Repository UserRole


Here is an example of the repository what it will look like

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.Entity;

using System.Linq;

using System.Linq.Expressions;

using System.Web;


namespace TestService.Models


    public class RoleRepository : IRoleRepository


        AuthenticationContext context = new AuthenticationContext();


        public IQueryable<Role> All


            get { return context.Roles; }



        public IQueryable<Role> AllIncluding(params Expression<Func<Role, object>>[] includeProperties)


            IQueryable<Role> query = context.Roles;

            foreach (var includeProperty in includeProperties) {

                query = query.Include(includeProperty);


            return query;



        public Role Find(int id)


            return context.Roles.Find(id);



        public void InsertOrUpdate(Role role)


            if (role.Id == default(int)) {

                // New entity


            } else {

                // Existing entity

                context.Entry(role).State = EntityState.Modified;




        public void Delete(int id)


            var role = context.Roles.Find(id);




        public void Save()





        public void Dispose() 






    public interface IRoleRepository : IDisposable


        IQueryable<Role> All { get; }

        IQueryable<Role> AllIncluding(params Expression<Func<Role, object>>[] includeProperties);

        Role Find(int id);

        void InsertOrUpdate(Role role);

        void Delete(int id);

        void Save();



This will create all 3 repositories for the models under the model folder. You will see one more file that is [your project name]Context,

if you already have a context file remove this file and on each repository replace this file type with your class name.


Now build the project and you just implemented the repository pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *