A simple application with ASP.NET MVC 4 with EF 6 Code first and Scaffolding

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.

  1. Introduction to ASP.NET MVC
  2. How to create first Application by ASP.NET MVC
  3. Uses of ViewBag and Model in ASP.NET MVC
  4. Routes and Controllers in ASP.NET MVC

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 an 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)

02-Packagemangerconsole

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.

The following two files “Red marked” are Trainer and Training model.

1-Models

Trainer Model

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 Model

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

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, the following (red marked) controller and view will be created.

03-Controllers

Step 6: Modify Contex and Layout.

Comment out the UserContext Class in AccountModels.cs file.

//public class UsersContext : DbContext
//{
// public UsersContext()
// : base("DefaultConnection")
// {
// }

// public DbSet UserProfiles { get; set; }
//}

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)

04-Layout

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, table of the corresponding mode will be created like below.

05-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! :)

Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

2 thoughts on “A simple application with ASP.NET MVC 4 with EF 6 Code first and Scaffolding

  1. Samiul says:

    Nice tutorial!
    Please write tutorials about best pattern to follow when developing large scale MVC app (like repository pattern).

    Thanks!

    • This article for the people who just want start with MVC and EF. I will write another article in which repository pattern will be introduced or will modify the article. Thanks for your valuable comments.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>