Hello Friends, In this tutorial we are going to see how to Save Data using Entity Framework in ASP.NET MVC. We are already familiar with the Entity Framework. Here we will see how we can save Data using Entity Framework in ASP.NET MVC.

After completing this tutorial you will be able to understand:

  • How to Save data using Entity Framework in  ASP.NET MVC.

Save Data using Entity Framework in ASP.NET MVC.

In our previous session, we have seen that how to bind Dropdownlist using Entity Framework. Here we will Save the Data to SQL Server using Entity Framework in ASP.NET MVC.

Let’s Start with Creating Database and Tables in SQL Server.

Step 1 – Create Database using the following script.

CREATE DATABASE MYDB

Step 2 – Create Employee table using the following script.

USE [MYDB]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Employee](
[EmployeeID] [bigint] IDENTITY(1,1) NOT NULL,
[EmployeeName] [varchar](50) NULL,
[Gender] [varchar](10) NULL,
[Address] [varchar](50) NULL,
[State] [varchar](50) NULL,
[City] [varchar](50) NULL,
[Status] [varchar](20) NULL,
CONSTRAINT [PK__Employee__3214EC274AA9A371] PRIMARY KEY CLUSTERED 
(
[EmployeeID] 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

Step 3 – Open Visual Studio and Create a ASP.NET MVC SaveRecrodUsingEntitryFramework as shown in the below image.

Save Record using Entity Framework

Step 4 – Create an Empty template and click OK.

Step 5 –  First of all, we need to Install Entity Framework. Goto Tool > Library Package Manager > Manage NuGet Packages For Solutions..

Save Record using Entity Framework

Save Record using Entity Framework

Step 6 – Right Click on the Model folder and Create a class with the name Employee and write the following code in Employee class.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;


namespace SaveRecrodUsingEntitryFramework.Models
{
[Table("Employee")]
public class Employee
{
[Key]
public Int64 EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Status { get; set; }


}
}

Step 7 – Right Click on the Model Folder and Create a Class EmployeeDbContext and write the following code in EmployeeDbContext class.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace SaveRecrodUsingEntitryFramework.Models
{
public class EmployeeDbContext:DbContext
{
public DbSet<Employee> Employee { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<EmployeeDbContext>(null);
base.OnModelCreating(modelBuilder);
}
}
}

Step 9 – Add the following Connection String in web.config class with the name EmployeeDbContext.

<connectionStrings>
<add name="EmployeeDbContext" connectionString="data source=DESKTOP-9VC12LL\SQLEXPRESS;Initial Catalog=MYDB;integrated security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 8 – Right Click on the Controller folder and Create a Controller with the name HomeController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SaveRecrodUsingEntitryFramework.Models;

namespace SaveRecrodUsingEntitryFramework.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
 
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Employee objEmployee)
{
using (EmployeeDbContext objEmployeeDbContext = new EmployeeDbContext())
{
objEmployeeDbContext.Employee.Add(objEmployee);
objEmployeeDbContext.SaveChanges();
Int64 id = objEmployee.EmployeeID;
}
return View(objEmployee);
}
}
}

Step 9 – Right Click on the Index Action method and add a View with the name Index.

Save Record using Entity Framework

Steo 10 – Write the following code to Index.cshtml file.

@model SaveRecrodUsingEntitryFramework.Models.Employee


@{
ViewBag.Title = "Index";
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<h2>Index</h2>
<style>
.row {
margin-top:10px;
}
</style>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-class">
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.EmployeeName)
</div>
<div class="col-md-2">
@Html.TextBoxFor(model => model.EmployeeName, new { @class="form-control"})
</div>

</div>
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.Gender)
</div>
<div class="col-md-2">
@Html.DropDownListFor(model => model.Gender, new List<SelectListItem>
{ new SelectListItem{Text="Male", Value="Male"},
new SelectListItem{Text="Female", Value="Female"}
},
"Please select", new { @class = "form-control" })
</div>

</div>
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.Address)
</div>
<div class="col-md-2">
@Html.TextAreaFor(model => model.Address, new { @class = "form-control" })
</div>

</div>
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.State)
</div>
<div class="col-md-2">
@Html.DropDownListFor(model => model.State, new List<SelectListItem>
{ new SelectListItem{Text="UP", Value="UP"},
new SelectListItem{Text="MP", Value="MP"},
new SelectListItem{Text="MH", Value="MH"}
},
"Please select", new { @class = "form-control" })
</div>

</div>
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.City)
</div>
<div class="col-md-2">
@Html.TextBoxFor(model => model.City, new { @class = "form-control" }) </div>

</div>
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.City)
</div>
<div class="col-md-1">
@Html.RadioButtonFor(m => m.Status, "Active")

Active

</div>
<div class="col-md-1">
@Html.RadioButtonFor(m => m.Status, "Inactive")
Inactive
</div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-2">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
</div>


}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Run the Application. The output window should look like this.

Save Record using Entity Framework

View More:

Conclusion:

I hope you understand this tutorial. I would like to have your valuable comments, feedback and suggestions.

Thank You.

Leave a Comment