Creating a Generic Repository with Entity Framework and MVC

Hey there! So, I really like Generic Repositories.  They are a very useful design pattern and are enjoyable to use once configured properly.  However, when I first started learning about this design pattern I found a lot of the tutorials out there to be overly convoluted. The goal of this article is to get you up and running with a simple but powerful Generic Repository.

This tutorial assumes general working knowledge of Entity Framework and is based around MVC, though it could be applied to other frameworks and patterns.

As a side note or disclaimer, most of the code shown here is actually slightly modified code from the open source NopCommerce ecommerce platform.  I think NopCommerce has a great implementation of a generic repository, so why rewrite the whole thing?  The whole point of this in the first place is to avoid rewriting code.  Don’t worry if you don’t even know what NopCommerce is – the code here is stand alone and has no dependency on the platform. I have simply extracted some of it out and simplified it for a tutorial.

Let’s quickly review the purpose and benefits of a Generic Repository.

Efficient MVC Redirects Using an HTTP Module

Redirects are a common necessity for websites operating in the real world.  Perhaps your marketing team wants a URL changed, or perhaps there has been an architectural change in your application that impacts its URL structure.  Maybe you’re just experimenting with SEO.  Regardless of the reason, there are a lot of ways to handle redirects in MVC.

The most common way I have seen people handing redirects is inside of an action method of their controllers.  This is probably the easiest and most straightforward way to do things.  You might see some code like this:

public ActionResult About()
    ViewBag.Message = "Your application description page.";

    return RedirectToAction("Contact");

public ActionResult Contact()
    ViewBag.Message = "Your contact page.";

    return View();

There is nothing really wrong with this strategy, especially if you’re okay with recompiling code.  However, this isn’t the most efficient way to handle redirects from a performance standpoint.  The reason for this is because ASP.NET still needs to process the entire MVC framework pipeline, just to have another request start up again.  This is not an article on the ASP.NET Request Life Cycle, but for those who are unaware, MVC Controller instantiation and Action Method invocation actually happen fairly late into the overall request pipeline.  The MVC framework is implemented through the MvcHttpHandler, which gets excuted late in the HttpApplication life cycle events.  We wanted to prevent this Handler from ever being executed.  To do this we can hook into an event that gets triggered before it and handle our redirect there.  You can see a complete list of the events at this link – we need our code to run before the PreRequestHandlerExecute event.  This is the event that begins execute of the MVC handler.

Deploying an MVC Code First application to Windows Azure

Deploying an Entity Framework Code First application to Azure can be confusing. Maybe this is just my opinion but hey, it’s my blog.  I recently had to do this for a project and I found a lot of pieces of information that helped, but few complete tutorials or guides on how all the pieces fit together.  Hopefully this will help someone out.  Basic working knowledge of MVC, Entity Framework, and Azure are assumed.

Initially my main point of confusion was the number of moving parts – Entity Framework, a local and remote database, an Azure website, Azure accounts, connection strings, publishing profiles etc.  Let’s take a closer look at how all these work together.

Since there are a lot of steps I will try to number them so you don’t skip anything when you inevitably start skimming rather than reading (we all do it).  I have tried to break them into 10 logical steps that are fairly easy to remember.

1) Go ahead and create a blank MVC Application in Visual Studio.  Choose No Authentication so we can go through the process of creating and deploying a database ourselves with Entity Framework rather than using pre-built code.

2) Add Entity Framework to your solution by right clicking on your project References and saying “Manage Nuget Packages”.  Install the latest Entity Framework…at the time of this writing its 6.1 but the version doesn’t really matter for this tutorial as long as you’re on a version that supports Code First Migrations.  For me Entity Framework was the first choice on the Packet Manager pop up.

3) Next we need to create a couple classes that will serve as Models – something that will map to database tables.  Create a Book class and an Author class in the Models folder, as shown below:


4) Next we need to create our DbContext class, which sort of acts as a window into our database and its tables.  We’ll call it LibraryContext.cs and create a DbSet for the Author and Book class – just add the class to the top level of your project.

Library Conext

5) Create a connection string with the same name as the DbContext class.  This is important.  There are a number of ways to configure a connection from Entity Framework to a database, but I like this one because it avoids hard coding strings and is easier to spot in the web.config.  For now just point it to your local database and give the initial catalog the name of Library.  It doesn’t matter if you use localdb or SQLExpress or full SQL.


    <add name=”LibraryContext” connectionString=”Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Library.mdf;Initial Catalog=Library;Integrated Security=True” providerName=”System.Data.SqlClient” />


6) Next we need to write code that actually accesses our database so that Entity Framework creates it on demand.  Modify your home controller so that it looks like this:

Data Access

Make sure to add the code to the About action that actually retrieves a book you have saved – this will come in handy later when we want to verify our database was updated on Azure.

7) Run your application and make sure it created the database by connecting to localdb with server explorer and expanding the tables.

LocalDB Database

8) Next we have to enable migrations in Entity Framework.  This will allow code to update or create the schema of our database.  This is necessary for Azure, which will not create a database on demand with Code First, so you have to provide it with explicit miration code that will recreate the tables and schema in an existing, empty database.

From the Package Manager Console (Tools -> Library Package Manager) run the following commands:


Visual Studio will think for a moment – after it’s complete run this:

Add-Migration “initialcreate”

These commands will enable Code First Migrations and add a Migrations Folder to your solution.  If you (carefully) peek inside of this you will see a configuration.cs file and another InitialCreate.cs file.  The configuration file appropriately assigns some general settings, and the InitialCreate.cs file defines some code to create the necessary tables in our database.  This is basically code that explicitly performs the operations Entity Framework does behind the scenes locally when you first create a database that doesn’t exist.

This is most of what we have to do in Visual studio, so its time to head to Azure.  We’re almost done!

9) Sign into Azure with an administrator account and create a new custom database by pressing the big +New button in the bottom left.  You can also create the website first but I find it easier (and more logical) to create the database first.  If you are new to Azure you may also need to create a database server, which is easy to do through the UI. Call the database Library like we did in our connection string for simplicity, though this isn’t imperative.  It’s important that you use an account with full database permissions – preferably the account that created the server.

Create Database-1

8) Create a new custom website using the same button in the lower left and call it whatever you want.  Choose Library as the database and enter in your database server credentials.  Make sure you name the connection string the same as you did in Visual Studio – in our case this is LibraryContext

Create Website

10) After both of these have been created you will have a blank website hooked up to a blank database. Fun stuff!  Now download the Publishing Profile from the dashboard of the website.  If you open it up you will see that it is a regular XML file.  If you view it in a formatted text editor you will see that it just includes various information about the application and can actually be edited pretty easily.

Inside Visual Studio, right click on your project and select “Publish”.  In the dialog box that pops up,choose Import and import the file you just downloaded.  You can browse the tabs to see all the info it brought in.  There are a couple changes we need to make.  Leave the Profile and Connection tabs alone and go to Settings.  Make sure you choose “Release” configuration.  Under Databases, choose the Library connectino string from the drop down.  Make sure both “Use this connection string at runtime” and “Execute Code First” are checked.  Execute Code first is unchecked by default – make sure you select it.

Under the Preview tab there isn’t much to see but if you hit Start Preview you can see what files Visual Studio will deploy.  This is more useful for when deploying updates than it is for initial deployments.

As a side note, after you run this wizard Visual Studio will create a Publishing Profiles folder under the Properties section of your project.  Here you can edit the profile XML files.  There are a few useful settings in here that can’t be edited through the wizard, such as whether to deploy the App_Data folder.

Publishing Profile

Finally, click publish!.  Visual Studio will go through its deployment process and then open up to your website.  With any luck, the code should have run and created your database!

There are two easy ways to verify the database schema and data were created.  The first is by connecting to the database through Sql Management Studio using the database server name you find on the Azure dashboard and the login you used in your connection string.  You can also verify it by navigating to the About page on your site – if you see your book title it means it was retrieved from the database successfully.  Remember, this is why we added the code to retrieve the book.

That wasn’t so bad, right?

Once you understand all the pieces, deploying these types of applications from Visual Studio is actually much nicer and less painful than other types of deployments and hosting configurations.

Updating Posted Form Values on Postback with MVC – Fixing “Cached” Values

While working on a project I encountered a strange issue.  I created a simple registration form that posted back to my controller method, which received a view model as a parameter.  In my method I needed to update the values on this View Model before passing it back to the user through the same View.  However, this is where I encountered “strange” results.  Despite the correct data binding, correct code updating the model values, and the correct model being passed into the view, front-end users still received the old form values they initially posted.

This was initially puzzling, because I could see that the model I was passing in was correctly updated.   At first I assumed it was some kind of caching issue and tried a number of options, but to no avail.  Eventually I figured out the problem was coming from the Razor Helper I was using – specifically the EditorFor method (although this applies to any Razor helper method).

Let’s take a closer look.

General Thoughts on Passing Exam 70-486 (MVC Web Applications)

It’s a beautiful day!

This week I was fortunate enough to pass the Microsoft Certification Exam 70-486, which focuses on web application development with MVC and Azure.  Due to the non-disclosure agreement I signed (digitally) I can’t reveal and specific questions or example from the test, but I can offer some general thoughts and guidance for preparation.

Personally I thought this was a very difficult test, but I admit that I don’t have real world experience with a number of topics the exam covers.  I have worked fairly extensively with MVC, so I thought I would have a great shot at passing.  However, I may have mislead myself a bit.  MVC may be in the title of the exam, which I think led me to believe it would be very MVC centric, but this is not entirely true.  The exam focuses very heavily on related topics like Azure, Authentication methodologies, security, and IIS concerns like routing.  This is no secret – if you look at the official Microsoft exam guide it will tell you as much – but I just want to remind people that straight MVC (views, models, controllers, actions, filters, routing, etc.) is only part of this test.  Subconsciously it’s easy to gravitate towards studying topics you’re already familiar with.

Long story short: The exam has MVC in the name but that’s really only a fraction of the test.