Crud Operation with Entity Framework in MVC
Today we discuss about Crud Operation with Entity
Framework in MVC4.0
Create DataBase for this crud operation:-
create database dbMVC
use dbmvc
Create table for this :-
Create table student_info(id int primary key identity(1,1),name varchar(4),age int, check (age<100))
insert into student_info(name,age) values ('Rahul',23)
First open new
project in Visual Studio 2010/2012
Then select ASP.NET MVC3/4 WEB Application Visual C#
Add a class with name database.cs
Code for database.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using
System.ComponentModel.DataAnnotations;
using System.Web;
namespace
crudoperationinmvc.Models
{
public class database:DbContext
//here we use DBContext to use DbContext(string nameOrConnectionString) Constructor
{
public database()
: base("ConStr")// ConStr is name of
Connection String.
{
}
public DbSet<student> stu_info { set; get; }
}
}
Now add ConnectionString in Web.Config
Code for web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your
ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework
configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name ="ConStr"
providerName="System.Data.SqlClient"
connectionString="Data
Source=ramulaptop\ramukumar;
Initial Catalog=dbMVC;
Persist Security Info=True;
User Id=sa;
password=mysachi"/>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data
Source=(LocalDb)\v11.0;Initial
Catalog=aspnet-crudoperationinmvc-20140203174153;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-crudoperationinmvc-20140203174153.mdf" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider,
System.Web.Providers, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider,
System.Web.Providers, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider,
System.Web.Providers, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<!--
If you are deploying to a cloud
environment that has multiple web server instances,
you should change session state
mode from "InProc" to "Custom". In addition,
change the connection string named
"DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure
and SQL Compact) instead of to SQL
Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider,
System.Web.Providers, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,
EntityFramework" />
</entityFramework>
</configuration>
Now add Student class
code for student.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using
System.ComponentModel.DataAnnotations;
using
System.ComponentModel.DataAnnotations.Schema;
using System.Web;
namespace
crudoperationinmvc.Models
{
[Table("student_info")]
public class student
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id{get;set;}
public string name { get; set; }
public int? age { get; set; }
}
}
now add an Interface name IDataAccess.cs
Code for IDataAccess.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace crudoperationinmvc.Models
{
interface IDataAccess
{
List<student> GetStudentList();
student GetStudentDetails(int id);
void InsertStudent(student st);
void DeleteStudent(int id);
void UpdateStudent(int id, student st);
}
}
now add one class with name crudFunction.cs
and implement this IDataAccess Interface.
Code for crudFunction.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace
crudoperationinmvc.Models
{
public class CrudFunction:IDataAccess
{
database db = new database();
public List<student> GetStudentList()
{
return db.stu_info.ToList ();
}
public student GetStudentDetails(int id)
{
return
db.stu_info.FirstOrDefault(m => m.id == id);
}
public void InsertStudent([Bind(Exclude="id")]student st)
{
db.stu_info.Add(st);
db.SaveChanges();
}
public void DeleteStudent(int id)
{
var v = db.stu_info.FirstOrDefault(m =>
m.id == id);
if (v != null)
{
db.stu_info.Remove(v);
db.SaveChanges();
}
}
public void UpdateStudent(int id, student st)
{
var v = db.stu_info.FirstOrDefault(m =>
m.id==id);
if (v != null)
{
v.name = st.name;
v.age = st.age;
db.SaveChanges();
}
}
}
}
now right click on controller folder in solution explorer and add controller.
with name Defalult1 and MVC controller with empty read/write actions and click add button.
code for Default1Controller.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using
crudoperationinmvc.Models;
namespace
crudoperationinmvc.Controllers
{
public class Default1Controller : Controller
{
IDataAccess idata;
//
// GET: /Default1/
public
Default1Controller()
{
idata = new CrudFunction();
}
public ActionResult Index()
{
var v = idata.GetStudentList();
return View(v.ToList ());
}
//
// GET: /Default1/Details/5
public ActionResult Details(int id)
{
var v = idata.GetStudentDetails(id);
return View(v);
}
//
// GET: /Default1/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Default1/Create
[HttpPost]
public ActionResult Create([Bind (Exclude="id")]student st)
{
try
{
// TODO: Add insert logic
here
idata.InsertStudent(st);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Default1/Edit/5
public ActionResult Edit(int id)
{
return View(idata.GetStudentDetails(id));
}
//
// POST: /Default1/Edit/5
[HttpPost]
public ActionResult Edit(int id, student st)
{
try
{
// TODO: Add update logic
here
idata.UpdateStudent(id, st);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Default1/Delete/5
public ActionResult Delete(int id)
{
return View(idata.GetStudentDetails(id));
}
//
// POST: /Default1/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic
here
idata.DeleteStudent(id);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Now right click on Index ActionResult and add strongtype view with name Index and select Model class name:- student(crudoperationinmvc.Models) and select Scaffold template:- list and click add
Code for Index.cshtml view:-
@model IEnumerable<crudoperationinmvc.Models.student>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create
New",
"Create")
</p>
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelitem => item.id)</td>
<td>@Html.DisplayFor(modelitem =>
item.name)</td>
<td>@Html.DisplayFor(modelitem => item.age)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.id }) |
@Html.ActionLink("Details", "Details", new { id = item.id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.id })
</td>
</tr>
}
</table>
@model crudoperationinmvc.Models.student
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>student</legend>
<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model =>
model.name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.age)
@Html.ValidationMessageFor(model =>
model.age)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to
List",
"Index")
</div>
Now right click on Edit ActionResult and add strongtype view with name Edit and select Model class name:- student(crudoperationinmvc.Models) and select Scaffold template:- Edit and click add
code for Edit.cshtml
@model crudoperationinmvc.Models.student
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>student</legend>
@Html.HiddenFor(model => model.id)
<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model =>
model.name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.age)
@Html.ValidationMessageFor(model =>
model.age)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to
List",
"Index")
</div>
Now right click on Details ActionResult and add strongtype view with name Details and select Model class name:- student(crudoperationinmvc.Models) and select Scaffold template:- Details and click add
code for Details.cshtml
@model crudoperationinmvc.Models.student
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>student</legend>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.name)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.age)
</div>
<div class="display-field">
@Html.DisplayFor(model
=> model.age)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.id }) |
@Html.ActionLink("Back to
List",
"Index")
</p>
Now right click on Delete ActionResult and add strongtype view with name Delete and select Model class name:- student(crudoperationinmvc.Models) and select Scaffold template:- Delete and click add
code for Delete.cshtml
@model crudoperationinmvc.Models.student
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Delete</title>
</head>
<body>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>student</legend>
<div class="display-label">
@Html.DisplayNameFor(model
=> model.name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.name)
</div>
<div class="display-label">
@Html.DisplayNameFor(model
=> model.age)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.age)
</div>
</fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to
List",
"Index")
</p>
}
</body>
</html>
0 comments:
Post a Comment