Web Tutorials

HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
.NET Tutorial
PHP Tutorial

Interview Q & A

ASP.NET Q & A
WEB API Q & A
WCF Q & A
JQuery Q & A
MVC Q & A
Bootstrap Q & A
LINQ Q & A
AJAX Q & A
SQL Server Q & A
C# Q & A
OOPS Q & A

Code Examples

AngularJS
Google MAP API V3
ASP.NET

Utility Tools

Html Encode
Html Decode
URL Decode
URL Encode
Base64 Encode
Base64 Decode
JSON Beautifier

Model first approach in entity framework 6 with ASP.NET MVC 5

Posted By: Ajay Saptaputre, 13 Oct,2014  |  Total View : 7904

In my previous article I discuss about how to create CRUD operation using Scaffolding with ASP.NET MVC 5 and database first approach using ASP.NET MVC 5 and Entity Framework 6

In this article I am going to discuss how to create web application using model first approach using entity framework 6 with ASP.NET MVC 5. This article let you know how to start with designing model by creating entities,relationship between entities and inheritance directly in design time using EDMX and generate database from model.

In model first approach we will create entity data model, data context and entity classes to generate database using Entity Framework 6. The beauty of this approach is entity data model can be automatically updated database whenever schema entity model changes. This article is using ASP.NET MVC 5 and Entity Framework 6 which will create database table when application run first time. Also I will cover complete CRUD operation with model first approach.

Open Visual Studio and start creating new MVC 5 project. In this article I am using Visual Studio Express 2013 for Web but you can use Visual Studio 2013 as well.

Now start creating ASP.NET MVC 5 project in Visual Studio 2013.

Step 1: Start Visual studio 2013, click on "New" Project from "File" menu and select "Web" and then "ASP.NET web application" from "New Project". I am selecting .Net framework 4.5 to build this sample application. All right, now give proper name as "ModelFirstMVCApplication" to application and click "Ok" button as below screen shot illustrate:


Step 2: Once done, you will see another window which asked to select "Template". Select "Empty" and checked "MVC" then click on "Ok" button as bellow screen shot illustrate:


Step 3: In order to use Entity Framework 6 in our project, you need to and add Entity Framework 6(If you have not installed on your system) from "Manage NuGet Packages...". To proceed this, right click on your project and select "Manage NuGet Packages..." from menu.


Step 4: From "Manage NuGet Packages" dialog box select "Online" option and then type "Entity Framework 6" from search text box and click on "Install" button after search result display. Now search for ASP.NET MVC, it will search MVC 5 version now click "Install" button. This will installed all the require DLL references to the project. Click "Close" button. This will install all require DLL references in your project



Step 5: All right, In order to start, right click on "Models" folder and select "New Item" from popup.


Step 6: Now, select "ADO.NET Entity Data Model" from item and give proper name to your Model.


Step 7: Select "Empty model" from Model wizard click "Finish" button. This will create empty model designer.


Step 8: Now, right click on designer and select "Add New" and then "Entity":


Step 9: In "Add Entity" dialogue box, enter name of the entity I am giving "Workers" here. Also you can change the default settings for Entity set and key property. We will keep the default settings as it is for now.


Step 10: Now start adding entity properties in entity, so right click on entity designer surface and select "Add New" and then "Scalar Properties". Enter the name of scalar property as shown below.



Step 11: After adding the required properties, associations and inheritance (if require) our model will looks like below. Okay, now time to generate database from our model entity. So right click on EDMX designer surface and select "Generate Database from Model" option from context menu.


Step 12: The above step will open "Generate Database Wizard". Using this dialog you can create new database or you can use existing database as well. In this sample I am selecting existing database. If you need to create new database you need to enter name of the database to create and then click "Ok" button see bellow screen shot:


Step 13: Once done, click on "Next" button to generate database script (DDL) for the model as shown below.


Step 14: Save the generated DDL, this will save the "SampleDBModel.edmx.sql" file in the Model folder of project. Now open "SampleDBModel.edmx.sql" file in VS and right click and select "Execute" from context menu. See below screen shot:


Step 15: The above step will generate "Workers" entity and model context class automatically based on connection string name we given. See below screen shot:


Step 16: If you open "Workers.cs" entity class it will looks like below:


Step 17: Now open "SampleDBModel.context.cs" class it will looks like below:


Step 18: All right, we are done our database creation from model first approach. Now right click on project and build the application. Now right click on Controller folder and select Add and then "Controller".


Step 19: Now, select scaffold controller template from "Add Scaffold" dialog box and click "Add". It will ask for controller name, give proper name to controller as "WorkersController" in this sample application.


Step 20: In the above step as we selected Scaffold template, it will automatically generate below code to the "WorkersController.cs" file. Notice that the attribute "ValidateAntiForgeryToken" added automatically by ASP.NET MVC 5 code generator, I will discuss more about "ValidateAntiForgeryToken in another Article.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCModelFirst.Models;

namespace MVCModelFirst.Controllers
{
public class WorkersController : Controller
{
	private SampleDBModelContainer db = new SampleDBModelContainer();

	// GET: /Workers/
	public ActionResult Index()
	{
		return View(db.Workers.ToList());
	}

	// GET: /Workers/Details/5
	public ActionResult Details(int? id)
	{
		if (id == null)
		{
			return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
		}
		Workers workers = db.Workers.Find(id);
		if (workers == null)
		{
			return HttpNotFound();
		}
		return View(workers);
	}

	// GET: /Workers/Create
	public ActionResult Create()
	{
		return View();
	}
	[HttpPost]
	[ValidateAntiForgeryToken]
	public ActionResult Create
	([Bind(Include="Id,Name,Address,BloodGroup,City,State,Zip")] Workers workers)
	{
		if (ModelState.IsValid)
		{
			db.Workers.Add(workers);
			db.SaveChanges();
			return RedirectToAction("Index");
		}

		return View(workers);
	}

	// GET: /Workers/Edit/5
	public ActionResult Edit(int? id)
	{
		if (id == null)
		{
			return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
		}
		Workers workers = db.Workers.Find(id);
		if (workers == null)
		{
			return HttpNotFound();
		}
		return View(workers);
	}

	[HttpPost]
	[ValidateAntiForgeryToken]
	public ActionResult Edit
	([Bind(Include="Id,Name,Address,BloodGroup,City,State,Zip")] Workers workers)
	{
		if (ModelState.IsValid)
		{
			db.Entry(workers).State = EntityState.Modified;
			db.SaveChanges();
			return RedirectToAction("Index");
		}
		return View(workers);
	}

	// GET: /Workers/Delete/5
	public ActionResult Delete(int? id)
	{
		if (id == null)
		{
			return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
		}
		Workers workers = db.Workers.Find(id);
		if (workers == null)
		{
			return HttpNotFound();
		}
		return View(workers);
	}

	// POST: /Workers/Delete/5
	[HttpPost, ActionName("Delete")]
	[ValidateAntiForgeryToken]
	public ActionResult DeleteConfirmed(int id)
	{
		Workers workers = db.Workers.Find(id);
		db.Workers.Remove(workers);
		db.SaveChanges();
		return RedirectToAction("Index");
	}

	protected override void Dispose(bool disposing)
	{
		if (disposing)
		{
			db.Dispose();
		}
		base.Dispose(disposing);
	}
}
}

Step 21: Notice that, because we selected Scaffold controller, the ASP.NET MVC 5 entity framework will also generate "Views" for us automatically you don't need to add view manually for CRUD operations. See below screen shot:


Step 22: All right, our sample ASP.NET MVC 5 model first application is ready to fly. Run the application and from browser add controller and action method name in URL as bellow. This will display all the workers from database as we are passing to our view.


Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

Download Code ⇩