MVC 4 APPLICATION USING ENTITY FRAMEWORK 5.0 WITH DATABASE FIRST APPROACH

INTRODUCTION
Now a day’s most of the developers will go for Code First approach in the entity framework where the database is very small and easy to manage. In this case developers will create the model first and create the database out of it.
What in the case of large projects? Here developers will prefer to opt for Database first approach where the database is created first and data model is created out of the database.

OVERVIEW
We will be using Visual studio 2012, MVC 4 and entity frame framework 5 for this example.
We will be using Sql Server 2008 R2 for database creation.

Creating a MVC 4 Project

To start with open the visual studio 2012 and select new project from the file menu. The new project dialog box opens as shown below.
1_New_Project
Select ASP.NET MVC 4 Application and provide desired name for your project and click on the OK button. The project Template dialog box opens as shown below.

2_Project_Template
Select Internet Application from the Project Template and click on the OK button.Visual studio opens the MVC 4 project with the name which you have provided.Remove the Default created pages by .net framework 4.5.

Create a database for the project.

We will be creating the database by name “MVC_EF_DatabaseFirst” in Sql server 2008 R2.
Create a table by name Users which will maintain the details for the user.
Below is the script for the same.
USE [MVC_EF_DatabaseFirst]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[UserDetails]
(
[UserID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NOT NULL,
[Address] [varchar](1000) NULL,
[Town] [varchar](50) NULL,
[County] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[Rating] [int] NULL,
[DoB] [datetime] NULL,
CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED
(
[UserID] ASC
)
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Once you have done with creating the database and table, we will start working on project. Now we need to create the Entity Data Model class file from the Users table. To create Data model class file, we will do reverse engineering for code first.

Right click on the Project -> point to Entity Framework -> click on Reverse engineer Code first as shown below.

Reverse_code_first

This will open the connection Properties. Specify the connection details and click on the OK button as shown below.

Db_connection

This will generate the Entity data model with the mapping class add the connection string in your Web. Config file as shown below.

Mapping_Class

Open the HomeController.cs file and write the code to fetch the data from the model.

Index Page

We will start by creating an index page. Below is the screenshot for the Index page.

Index_no_records_page

Please add the below code to the Index.cshtml page.

Html_Index

In the above html code I have specified the title of the page followed by table which loops through the records for displaying the data.I have also provided the search functionality which will search for the specific record and display it in table.In the controller add the below code so that the index page will display data.

private MVC_EF_DatabaseFirstContext dbContext = new MVC_EF_DatabaseFirstContext();
public ActionResult Index(string strValue)
{
try
{
var GetUserDetails = from s in dbContext.UserDetails select s;
if (!String.IsNullOrEmpty(strValue))
{
GetUserDetails = GetUserDetails.Where(user => user.Name == strValue || user.Address == strValue || user.Town == strValue || user.Country == strValue || user.County == strValue);
}
return View("Index", GetUserDetails);
}
catch (Exception)
{
return View();
}
}

In the above code we have called UserDetails entity through the context and fetch the data into the view.

Add User

Now i will create the Add user page to add new user to the database.  Right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as AddUser.cshtml. Below is the screenshot for the same.

Add_New_User

Now add the below code in the controller for add user page working.

public ActionResult AddUser()
{
return View();
}

[HttpPost]
public ActionResult AddUser(UserDetail objUserdetails)
{
try
{
if (ModelState.IsValid)
{
dbContext.UserDetails.Add(objUserdetails);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(objUserdetails);
}

In the above code we have created the object of the UserDetails entity and used that object to fill the data into the context.

ModelState.IsValid will validate the data entered by the user. Now I need to provide other validations such length of the string etc on the field.

For that open the UserDetails.cs file under Models folder.

Add the data annotations to each field as shown in the below code.

public partial class UserDetail
{
public int? UserID { get; set; }

[Display(Name="User Name")]
[Required]
[StringLength(50, ErrorMessage = "User name cannot be longer than 50 characters.")]
public string Name { get; set; }

[Display(Name = "User Address")]
[Required]
[StringLength(1000, ErrorMessage = "User Address cannot be longer than 1000 characters.")]
public string Address { get; set; }

[Display(Name = "User Town")]
[Required]
[StringLength(50, ErrorMessage = "User Town cannot be longer than 50 characters.")]
public string Town { get; set; }

[Display(Name = "User County")]
[Required]
[StringLength(50, ErrorMessage = "User County cannot be longer than 50 characters.")]
public string County { get; set; }

[Display(Name = "User Country")]
[Required]
[StringLength(50, ErrorMessage = "User Country cannot be longer than 50 characters.")]
public string Country { get; set; }

public Nullable<int> Rating { get; set; }

[Display(Name = "User Date of Birth")]
[Required]
[DisplayFormat(DataFormatString = "{0:dd MMMM, yyyy}")]
public Nullable<System.DateTime> DoB { get; set; }
}

The above code checks for required, string length and date format.

Edit User

When the user clicks on the Edit Hyperlink in the table it will navigate to the Edit user page.

To create the Edit User page, right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as EditUser.cshtml. Below is the screenshot for the same.

Edit_user

Create a view by name EditUser.cshtml and add the below code for the same.

Html_EditNow add the below code in the controller for displaying the records in the Edit mode and save it after changes.

public ActionResult EditUser(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);

if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditUser(UserDetail objUserdetails)
{
try
{
if (ModelState.IsValid)
{
dbContext.Entry(objUserdetails).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
}

catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View();
}

In the above code the Edit user page will display records in the edit mode for that particular user. Once the data is modified the user can save the changes in to the database.

User Details

User details page will display the all the details for that particular user when clicked on the Details link from the grid.

To create the User Details page, right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as EditUser.cshtml. Below is the screenshot for the same.

User_Details

Create a view by name UserDetails.cshtml and add the below code for the same.

Html_Details

Add the below code in the controller for user detail functionality.

public ActionResult UserDetails(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);

if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}

The above code will take user id as a input parameter and displays the data accordingly.

Delete User

Create a delete User page by name DeleteUser.cshtml and add the below code in the page.

Html_Delete

Add the below code in the Controller.

public ActionResult DeleteUser(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);
if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}

[HttpPost, ActionName("DeleteUser")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
try
{
UserDetail userDetail = dbContext.UserDetails.Find(id);
dbContext.UserDetails.Remove(userDetail);
dbContext.SaveChanges();
}
catch (DataException)
{
return RedirectToAction("DeleteUser", new { id = id, saveChangesError = true });
}
return RedirectToAction("Index");
}

The above code will take user id as a parameter and displays all the user details on the page.

When the user clicks on the delete button DeleteConfirmed action result will get fired deleting the user and redirection it back to the index page.

The source code can be downloaded from Here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s