In this article, we have to study how to create basic CRUD functionality using EntityFramework Code First and MVC 4.
Open Visual Studio and create a new project named "MVCDemo" using the ASP.NET MVC 4 Web Application template -
In the New ASP.NET MVC 4 Project dialog box select the empty template and the Razor view engine, clear the Create a unit test project check box, and then click OK.
Right Click Project Root Folder -> Manage NuGet Packages -> Search EntityFramework Online -> Choose EntityFramework -> Click Install.
After clicking Install, this will add Newer version of EntityFramework to your References.
After clicking Add, this will generate Create View in your View folder. Now Run the Project and Click Create new link you can see below screen.
Open Visual Studio and create a new project named "MVCDemo" using the ASP.NET MVC 4 Web Application template -
In the New ASP.NET MVC 4 Project dialog box select the empty template and the Razor view engine, clear the Create a unit test project check box, and then click OK.
Entity Framework Code First
In Code First, first thing you do is write code to describe your entities, and you can simply define the classes and let EF work with those, it is called “Code First development”.
Install EntityFramework
Now add EntityFramework in your References as follow -
Right Click Project Root Folder -> Manage NuGet Packages -> Search EntityFramework Online -> Choose EntityFramework -> Click Install.
After clicking Install, this will add Newer version of EntityFramework to your References.
Create Model
Create a class file named MvcDemoClass.cs in Model folder (actually you should create different files for different models, I created all of them just to save my time). See below screenshots.
Now, add below code to your MvcDemoClass.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVCDemo.Models
{
public class Account
{
public int AccountId { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Post { get; set; }
public string Category { get; set; }
}
public class MvcDemoContext : DbContext
{
public DbSet<Account> Accounts { get; set; }
public DbSet<Blog> Blogs { get; set; }
}
}
In above we have created two tables Accounts and Blogs.
Now, add connectionString to webconfig file as follow -
<configuration>
<connectionStrings>
<add name="MvcDemoContext" connectionString="Data Source=DEVANG\SQLEXPRESS;Initial Catalog=MvcDemoContext;User ID=sa;Password=sa123" providerName="System.Data.SqlClient"/>
</connectionStrings>
Note : Name of connection string must be same as Context class in your model folder.
Add Controller
Now, Create a Controller in your Controller folder as follow-
Right click Controller -> Add - > Controller -> Name it as "HomeController".
Select Template as "Empty MVC Controller" and click Add.
After clicking Add button Visual Studio will generate the default code in your HomeController as follow -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCDemo.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
Change above code with below code -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDemo.Models;
using System.Data.Entity;
namespace MVCDemo.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
using (MvcDemoContext context = new MvcDemoContext())
{
return View(context.Accounts.ToList());
}
}
In above code, we will add namespace MVCDemo.Models to access Models folder classes in HomeController and also we have add System.Data.Entity namespace.
Create Index View in View Folder as follow -
Right click on Index() action -> Click Add View.
After clicking Add View, this will show below popup. Choose Settings as follow -
- View Engine - Razor (CSHTML)
- Model Class - Account (MVCDemo.Models)
- Scaffold template - List.
- Click Add.
This will generate the View for Show List for Accounts table.
@model IEnumerable<MVCDemo.Models.Account>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Password)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Password)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AccountId }) |
@Html.ActionLink("Details", "Details", new { id=item.AccountId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AccountId })
</td>
</tr>
}
</table>
Now, Run the Project you will show the below screen in your browser -
Now generate the Create Action as follow -
Add below code to your HomeController and Add Create View as shown below step by step screenshot.
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Account account)
{
try
{
using (MvcDemoContext context = new MvcDemoContext())
{
context.Accounts.Add(account);
context.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
After adding above code right click "Create" Action (as describe when generate Index View) and Click Add View -> Choose below Settings.
- View Engine - Razor (CSHTML)
- Model Class - Account (MVCDemo.Models)
- Scaffold template - Create.
- Click Add.
After clicking Add, this will generate Create View in your View folder. Now Run the Project and Click Create new link you can see below screen.
Now generate the Edit Action as follow -
Add below code to your HomeController and Add Edit View as shown below step by step screenshot.
public ActionResult Edit(int id)
{
using (MvcDemoContext context = new MvcDemoContext())
{
return View(context.Accounts.Find(id));
}
}
//
// POST: /Home/Edit/5
[HttpPost]
public ActionResult Edit(int id, Account Accounts)
{
try
{
using (MvcDemoContext context = new MvcDemoContext())
{
context.Entry(Accounts).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
After adding above code right click "Edit" Action (as describe when generate Index View) and Click Add View -> Choose below Settings.
View Engine - Razor (CSHTML)
Model Class - Account (MVCDemo.Models)
Scaffold template - Edit.
Click Add.
After clicking Add, this will generate Edit View in your View folder. Now Run the Project and Click any Edit link. So you can able to edit data.
Now generate the Delete Action as follow -
Add below code to your HomeController and Add Delete View as shown below step by step screenshot.
public ActionResult Delete(int id)
{
using (MvcDemoContext context = new MvcDemoContext())
{
return View(context.Accounts.Find(id));
}
}
//
// POST: /Home/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
using (MvcDemoContext context = new MvcDemoContext())
{
Account accounts = context.Accounts.Find(id);
context.Accounts.Remove(accounts);
context.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
After adding above code right click "Delete" Action (as describe when generate Index View) and Click Add View -> Choose below Settings.
View Engine - Razor (CSHTML)
Model Class - Account (MVCDemo.Models)
Scaffold template - Delete.
Click Add.
After clicking Add, this will generate Delete View in your View folder. Now Run the Project and Click any Delete link. So you can able to delete data.
Now generate the DetailsAction as follow -
Add below code to your HomeController and Add Details View as shown below step by step screenshot.
public ActionResult Details(int id)
{
using (MvcDemoContext context = new MvcDemoContext())
{
return View(context.Accounts.Find(id));
}
}
After adding above code right click "Details" Action (as describe when generate Index View) and Click Add View -> Choose below Settings.
View Engine - Razor (CSHTML)
Model Class - Account (MVCDemo.Models)
Scaffold template - Details.
Click Add.
After clicking Add, this will generate Details View in your View folder. Now Run the Project and Click any Details link. So you can able to Show Data.
So, In this Demo We have generate basic CRUD Functionality using Entity Framework Code First and using MVC 4.
Done!
nice articles
ReplyDeleteI like to share with my frnds also
One of the best tutorials on the net, straight to the point!
ReplyDelete