A Simple Application With ASP.NET MVC 4 With EF 6 Code First And Scaffolding

4 minute read

Introduction
Before going to the details of article, I think you already know what MVC is and how ASP.NET MVC Works. If you don’t have any idea, you are requested to read the following article.

Project description
In this article I will develop a simple application with ASP.NET MVC 4 with Entity Framework 6 code first approach and scaffolding. I will also use MvcScaffold for quick develop of controllers, context and views. For your kind information, here I used visual studio 2012. Here I will develop two functionalities of an application “Training Management system” – Trainer Information and Training Information. User can view, save, edit and delete Trainer information and training information can be viewed, saved, edit and deleted same way. Both trainer and training information will show in simple grid. Trainer can be assigned to the training information

Entity Framework – code first
Entity Framework (EF) is an object-relational mapper (ORM) that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Three approach of entity framework are Model first, Database first, code first. In Code-First Approach, we create the classes first and then generate the database from the classes directly

Application development step by step

Step 1: Create a simple application name “TMS” by asp.net mvc.

I think, you must know How to create first Application by ASP.NET MVC) .

Step 2: Install “nuget” packages.

  • For installing “nuget”, you must have enable internet connection.
  • Open Package Manager Console (Tools-> Library Package Manager –> Package Manager Console)
  • Run following commands in the console – bottom of the window.
PM>Install-Package EntityFramework

PM>Install-Package MvcScaffolding

Step 3: Create two models “Trainer” and “Training” in Model folder.

  • Create Trainer and Training model class in Models folder.

Trainer.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
 
namespace TMS.Models
{
    public class Trainer
    {
    
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }

        public string Name { get; set; }

        public string Designation { get; set; }
        public string Oranizaton { get; set; }

        public DateTime CreateDate { get; set; }
        public DateTime ModificationDate { get; set; }

        public bool IsActive { get; set; }
    }
}

Training.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
 
namespace TMS.Models
{
    public class Training
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        
        public long Id { get; set; }
        public string Title { get; set; }
        public string Venue { get; set; }
        public long TrainerId { get; set; }
        
        [ForeignKey("TrainerId")]
        public virtual Trainer Trainer { get; set; }
        
        public string Description { get; set; }
        
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        
        public DateTime CreateDate { get; set; }
        public DateTime ModificationDate { get; set; }
        
        public bool IsActive { get; set; }
    }
}

In the above model, I used [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Which means attribute “Id” of the model is primary key and it is a identity column.

[ForeignKey(“TrainerId”)] means TrainerId is a Foreign key of Trainer. This two are called data annotation. You will know more about data annotation. I will write another article on data annotation soon.

Step 4: Change Connection String

Create a database name “TMSDB” and change connection string like following

<add name="TMSContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=TMSDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

Step 5: Create Controller and View using “Scaffold”

  • Open Package Manager Console (Tools-> Library Package Manager –> Package Manager Console)
  • Type the following command to Package Manager Console.
PM> Scaffold Controller Trainer
PM> Scaffold Controller Training

After running the above command, TrainersController, TrainingController and their corresponding view will be created.

Step 6: Modify Contex and Layout.

  • Modify TMSContext.cs file like following
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace TMS.Models
{
    public class TMSContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        //
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, add the following
        // code to the Application_Start method in your Global.asax file.
        // Note: this will destroy and re-create your database with every model change.
        //
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges());
        
        //Added for customized connection string "TMSContext"
        public TMSContext()
        : base("TMSContext")
        {
        }
        
        public DbSet UserProfiles { get; set; } //Added DbSet
        
        public DbSet Trainers { get; set; } //Auto generated by scaffolding
        
        public DbSet Trainings { get; set; } //Auto generated by scaffolding
    }
}


Build the application you will find error. So, replace UsersContext by TMSContext and build again. Now it builds successfully.

Added the marked two line in the _Layout.cshtml page (Views->Shared->_Layout.cshtml)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header>
            <div class="content-wrapper">
                <div class="float-left">
                    <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
                </div>
                <div class="float-right">
                    <section id="login">
                        @Html.Partial("_LoginPartial")
                    </section>
                    <nav>
                        <ul id="menu">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                            
                            <li>@Html.ActionLink("Trainer Information", "Index", "Trainers")</li>
                            <li>@Html.ActionLink("Training Information", "Index", "Trainings")</li>

                        </ul>
                    </nav>
                </div>
            </div>
        </header>
        <div id="body">
            @RenderSection("featured", required: false)
            <section class="content-wrapper main-content clear-fix">
                @RenderBody()
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
                </div>
            </div>
        </footer>

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
</html>

Step 7: Add migration and update database Run the following command in the package manager console.

PM> Enable-Migrations
PM> Add-Migration initialmigration
PM> Update-Database –Verbose

After running the above the command, database table will be created in the metioned database.

Now your project is ready. Run your project and go to the Trainer and Training information link and you can View, insert, update and delete an entry. Let’s try. Yes it’s working. Thanks for your patient! 🙂

Source code