Entity Framework (1), With .Net MVC, Code-First

After I wrote several articles on this site, I found out it seemed almost for every article, I needed to set up a sample application associated with an entity framework if accessing the database. And, every time, I needed to rewrite the setup process from scratch in order for a new reader to follow along easily. Even for introducing a very simple concept, such as Caching, I needed to spend 80% of the time setting up the sample app, and only 20%  on introducing the Caching concept itself.

Therefore, I think it is better to write a basic model such as entity framework sample for various approaches, and then I can reuse them when needed. I made a list of the series of articles below, I will write them one by one, while the Entity framework overview and concept will be covered in the article (0):


We write the Entity Framework for MVC module, but the pattern is the same or similar when applying to Web Application or Web API.


This article will be Entity Framework with .Net MVC, Code-First approach,

We will make a sample app step by step,

  • Step 1: Create an ASP.NET MVC application
  • Step 2: Add a Model
  • Step 3: Set up DbContext
  • Step 4: Set up Data Connection
  • Step 5: Create Controller to access data from entity framework
  • Step 6: Run the App and Test

At the end, we will have an MVC app that can consume a database directly through entity framework.

Step 1 - Create an ASP.NET MVC app

We use the current version of Visual Studio 2019 16.8 and .NET Framework 4.8 to build the app:

  • Start Visual Studio and select Create a new project.
  • In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next.
  • In the Configure your new project dialog, enter MvcMovie for Project name > Create.
  • In the Create a new ASP.NET Web Application dialog, select MVC > Creat

Note: For biginners, you may see details from here.

Build and run the app, you will see the following image shows the app,

Step 2: Add a Data Model

Add a data model, an entity class, into the app, with name as Movie:

  • In Solution Explorer, right click the Models folder, > Add,
  • In the Add New item dialog, Select Class, Enter the class name Movie > Add.

Add the following five properties to the Movie class:

using System;  
namespace MvcMovie.Models  
    public class Movie  
        public int ID { get; set; }  
        public string Title { get; set; }  
        public DateTime ReleaseDate { get; set; }  
        public string Genre { get; set; }  
        public decimal Price { get; set; }  

Step 3: Set up DbContext

Add another class for DbContext name as MvcMovieContext:

using System;  
using System.Data.Entity;  
namespace MvcMovie.Models  
    public class MovieDBContext : DbContext  
        public DbSet<Movie> Movies { get; set; }  

In order to use System.Data.Entity, and the related class, you need to install the Entity Framework NuGet Package from NuGet Package Manager:

From Visual Studio IDE, click Tools->NuGet Package Manager->Manage NuGet Packages for Solution

Click Browse, then search EntityFramework, then install,

Step 4: Set up Data Connection

Add the following connection string to the <connectionStrings> element in the Web.config file.

<add name="MovieDBContext"   
   connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf"   

If you add login part when you create the app, you will see the two connection strings. The first connection string is named DefaultConnection and is used for the membership database to control who can access the application. The connection string you've added specifies a LocalDB database named Movie.mdf located in the App_Data folder.

  <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie-fefdc1f0-bd81-4ce9-b712-93a062e01031;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcMovie-fefdc1f0-bd81-4ce9-b712-93a062e01031.mdf" providerName="System.Data.SqlClient" />  
  <add name="MovieDBContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf" providerName="System.Data.SqlClient" />  

You don't actually need to add the MovieDBContext connection string. If you don't specify a connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class (in this case MvcMovie.Models.MovieDBContext). You can name the database anything you like, as long as it has the .MDF suffix. For example, we could name the database MyFilms.mdf.

Step 5:  Create Controller to access data from entity framework

From Visual Studio IDE,

  • Right-click the Controllers folder.

  • Select Add > New Scaffolded Item Or Controller to open the window Add New Scaffolded Item

  • In the Add New Scaffold Item dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add.;

  • In the Add Controller dialog box,

    • Select Movie (MvcMovie.Models) for the Model class.
    • Select MovieDBContext (MvcMovie.Models) for the Data context class.
    • For the Controller name enter MoviesController.
    • Click Add.

(If you get an error, you probably didn't build the application before starting adding the controller.) Visual Studio creates the following files and folders:

  • A MoviesController.cs file in the Controllers folder.
  • A Views\Movies folder.
  • Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Movies folder

 Visual Studio automatically created the CRUD (create, read, update, and delete) action methods and views:


We will not exame the code in details, if you wanted, you may go here.

Step 6: Run the App, and Test

For convenience, you can update one line code in file Views/Shared/_Layout.chtml 

    <div class="navbar navbar-inverse navbar-fixed-top">  
        <div class="container">  
            <div class="navbar-header">  
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
                    <span class="icon-bar"></span>  
                    <span class="icon-bar"></span>  
                    <span class="icon-bar"></span>  
                @Html.ActionLink("MVC Movie", "Index", "Movies", new { area = "" }, new { @class = "navbar-brand" })  
            <div class="navbar-collapse collapse">  
                <ul class="nav navbar-nav">  
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>  
                    <li>@Html.ActionLink("About", "About", "Home")</li>  
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>  

Run the App, it will be like this:


Click MVC Movie:

Creating a Movie:

Select the Create New link. Enter some details about a movie and then click the Create button.


And finally:


We will write a series of articles for Entity Framework with various approaches, such as code-first or database-first. This is the first article dealing with .Net MVC, Code-First approach.