Code First Entity Framework with MVC4 and Visual Studio 2012

I am a huge fan of ADO.NET’s Entity Framework (EF) that bridges the gap between modelling entities\business logic and data engines. It allows web-programmers like myself to focus on the solution instead of worrying about properly setting up databases, keys, foreign-keys, constraints, and indexes. Because of it’s quick turn-around, EF is perfect for prototyping and proof of concepts. For enterprise sized solutions, code-first created databases may require some greater optimization, but that can always be achieved after the fact if not in the solution itself. Querying and operations are a simple endeavour–simply work with the abstracted model and let EF worry about performing the correct database transactions for you.


Visual Studio Logo


Setting up a Code First EF MVC4 project is simple enough, but because I don’t do it often, I sometimes forget some steps. After all, most of my time is spent working with the solutions, and not setting them up. For this reason, I have decided to make a graphical guide as well as this blog post, which I hope helps my readers as much ad it helps me. In this tutorial, I create a simple model that goes over many of the features that you might use.

Step 1 – Create a new Project

First create the project in VS2012 by going to new project, giving it a name, selecting ASP.NET MVC4, selecting Internet Application, and ensuring Razor is selected. This will give you the base for a Code First EF MVC4 application. In fact, the Accounts Model is already set up with Entity Framework!

Step 2 – Define the Model

Simple Model UML

Next we create a very simple model that exemplifies how a 1 to many relationship using ICollection. The UML diagram above is coded in code example below entitled, “TestModels.cs.” The model is a little inconsistent to illustrate different techniques and annotation of the entity framework: custom db table names, custom KEY, and custom FK name; as well, it illustrates that traditional EF naming, which doesn’t require the annotation described.

    [Table("dbUsers")] // Use this to use a different table name other than "Users"
    public class User
        public int DbUserId { get; set; }
        public string Name { get; set; }

        public virtual ICollection Purchases { get; set; }

    // This table will be called "Purchases" automatically
    public class Purchase
        // Because standard naming is used, no need for [Key] ...
        public int PurchaseId { get; set; } 
        public int UserId { get; set; }
        public int ProductId { get; set; }

        [ForeignKey("UserId")] // Use this if the name of FK is different
        public virtual User User { get; set; }
        // No need to use ForeignKey because FK name is same as Key of Product
        public virtual Product Product { get; set; }


    public class Product
        public int ProductId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection Purchases { get; set; }

Step 3 – Create the DbContext

In the same model file, I create a the DbContex object that tells EF which classes are going to be stored in the database. In this case, I name this “TestContext” as seen in code segment below. It may be useful to note that other options are available here such as turning off pluralization, pointing to a specific db connection, etc.

    public class TestContext : DbContext
        public DbSet Users { get; set; }
        public DbSet Purchases { get; set; }
        public DbSet Products { get; set; }


Step 4 – Add a Connection String

Next open up your “Web.config” and add a connection string in the <connectionStrings> node. If you followed the steps above, you should already have one named “DefaultConnection.” Whatever your choice of storage system, make sure you name your connection, “TestContext.” Entity framework will automatically associate this connection with the db context we created in step 3.

Step 5 – Add a Data Initializer

Entity Framework provides a very useful feature: the ability to initialize your tables with some sample data whenever the model changes. To do this create a new class that inherits from DropCreateDatabaseifModelChanges<DbContext>. Next we override the Seed(context) function where we add our products, purchases, and users. The method SaveChanges() in the DbContext object is run whenever you want to update the DB.

    public class TestInitializer : 
        protected override void Seed(TestContext context)
            var products = new List
                new Product { Name = "Widget", 
                              Description = "A widget is a widget." },
                new Product { Name = "Crank", 
                              Description = "A crank for the  widget." }
            products.ForEach(p => context.Products.Add(p));

            var users = new List
                new User { Name = "Joe" },
                new User { Name = "Lillith" }
            users.ForEach(u => context.Users.Add(u));

            var purchases = new List
                new Purchase {  
                    Product = 
                        products.Where(p => p.Name == "Widget").First(),
                    User =
                        users.Where(u => u.Name == "Joe").First() }
            purchases.ForEach(pr => context.Purchases.Add(pr));

Step 6 – Set the Initializer in Global.asax.cs

Next we set the initializer in the Global.asax.cs file to ensure that it runs when it needs (when the model changes and the context is used).

 public class MvcApplication : System.Web.HttpApplication
        protected void Application_Start()
            Database.SetInitializer(new TestInitializer());


Step 7 – Add the DbContext Object to a View in Order to Test

Usually I add the dbContext to the HomeController first (without even touching the Home View) in order to test out the implementation inside an ActionResult that I know I will run (visit with browser after running); I also add something to the data to ensure proper functionality and saving.

 public class HomeController : Controller
        private TestContext db = new TestContext();

        public ActionResult Index()
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            db.Products.Add(new Product { Name = "asdf" });
            return View();


The last step is to verify that the database, tables, and sample data were created properly in the DB. For this I usually run SQL Managment Studio and inspect the DB directly. If you did everything correctly, you should see a new database with the name that you’ve described in the connection string.

Below is the graphical Guide:

A graphical guide to the tutorial above


MSDN, Entity Framework Overview –
Creating an Entity Framework Data Model for an ASP.NET MVC Application –

Comments 19

  1. Pingback: Code First Entity Framework with MVC4 and Visual Studio 2012 | Rams On It - .NET

  2. DbContext implements IDisposable, therefore you have to call Dispose() on it by convention. You might even get into a situation where you have too many DB connections open if you don’t. Therefore it’s generally a bad idea to declare your context as a private member of a controller class. Better to instantiate a new one in each controller action and wrap it into a “using” statement.

    using (var db = new TextContext())
    // do your queries here

    1. Post

      You are right. The context gets disposed as soon as the view is rendered (always); however, it is better practice to wrap it around a using statement or instantiate it within each action and dispose it once done. In this respect my example is a little flawed.

      When I create my applications, I almost always wrap up the controller in a using statement as you show in your example; however, if someone does declare the context as part of the controller than it won’t be a problem if they instantiate (and dispose it) in every action.

      Thanks for your post. I hope that my readers pay attention to your post. One day I may get around to fixing this flaw in the example.

  3. Hello Dudde! Excellent post.
    Can You take a question regarding the image type?
    It is this: I have a class with a property of image type and when I try to create the controller, I get the following error message:

    “The type ‘System.Drawing.Image’ must be a non-nullable value type in order to use it as parameter ‘T’ in the generic type or method… ”

    How to manipulate this specific type on MVC4. I’m using EF POWER TOOLS to reverse engine (code first).

    Thanks for advance

  4. “instead of worrying about properly setting up databases, keys, foreign-keys, constraints, and indexes”
    Really ?
    You will never be a developer if you don’t.

    1. Post

      Hey Joey,
      I’m not saying I don’t or can’t. I’m saying when prototyping or getting something out quick, you don’t have to worry about it. Plus developers come in a myriad of types. If you work for a big company and your niche is front-end development, I doubt you would be doing very much DBA stuff. At our company, we have a DBA and I don’t need to worry about that stuff. Just DAL. Maybe you’ve only tinkered on your own projects and never really worked in the industry, but it’s very common for a real developer not to create DBs or set them up.

Leave a Reply

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