Entity Framework Model first approach to Read/Insert/Update/Delete database data in Asp.Net MVC & C#

Tarun Kumar Chatterjee
 
Net – Technology Specialist
May 14, 2016
 
Rate this article
 
Views
11336

Open Visual Studio 2013 and click on New Project.

Select the MVC Project Template and click on OK.

In this section, we will add the ADO.NET Entity Data Model to the application. We will create the empty model in here. Use the following procedure.

In the Solution Explorer, right-click on the Models folder and click on ADO.NET Entity Data Model.

clip_image002

Specify the model name as EmployeeModel.

In the next Entity Data Model Wizard, select the Empty Model and click on "Finish".

clip_image004

Now you can see the Entity Data Model Designer.

Within the designer Right click — > Add new — > Entity

In the next Add Entity wizard, specify the entity name.

clip_image006

Now you can see that the entity is created. So, it is time to add a scalar property to the entity. Right-click on the entity and go to add new scalar property.

clip_image008

Now we have generated an entity model. You can also create more entity models in the Data Model Designer. We will now generate the database from the model. Use the following procedure.

clip_image010

Now in the Generate Database Wizard, click on New Connection to connect with the database.

 

clip_image012

In the next Connection Properties wizard, specify the server name and the specify the database name.

clip_image014

 

The database summary and script is generated and click on Finish.

clip_image016

It will generate the database & create EmployeeModel.edmx.sql with the following script

— ————————————————–

— Entity Designer DDL Script for SQL Server 2005, 2008, and Azure

— ————————————————–

— Date Created: 01/27/2016 18:41:19

— Generated from EDMX file: D:\Project\EntityFrameworkDemo\EntityFrameworkDemo\Models\EmployeeModel.edmx

— ————————————————–

SET QUOTED_IDENTIFIER OFF;

GO

USE [MyEmployeeDB];

GO

IF SCHEMA_ID(N’dbo’) IS NULL EXECUTE(N’CREATE SCHEMA [dbo]’);

GO

— ————————————————–

— Dropping existing FOREIGN KEY constraints

— ————————————————–

— ————————————————–

— Dropping existing tables

— ————————————————–

IF OBJECT_ID(N'[dbo].[Employees]’, ‘U’) IS NOT NULL

DROP TABLE [dbo].[Employees];

GO

— ————————————————–

— Creating all tables

— ————————————————–

— Creating table ‘Employees’

CREATE TABLE [dbo].[Employees] (

[Id] int IDENTITY(1,1) NOT NULL,

[Name] nvarchar(max) NOT NULL,

[Address] nvarchar(max) NOT NULL,

[DOB] nvarchar(max) NOT NULL

);

GO

— ————————————————–

— Creating all PRIMARY KEY constraints

— ————————————————–

— Creating primary key on [Id] in table ‘Employees’

ALTER TABLE [dbo].[Employees]

ADD CONSTRAINT [PK_Employees]

PRIMARY KEY CLUSTERED ([Id] ASC);

GO

— ————————————————–

— Creating all FOREIGN KEY constraints

— ————————————————–

— ————————————————–

— Script has ended

— ————————————————–

 

Now right-click on the script and click on Execute or directly we can go to database & execute the script.

The EmployeeModel.Context file generated from the first template contains the EmployeeModelContainer class shown here:

 public partial class EmployeeModelContainer : DbContext
     {
         public EmployeeModelContainer()
             : base("name=EmployeeModelContainer")
         {
         }
     
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
             throw new UnintentionalCodeFirstException();
         }
     
         public DbSet<Employee> Employees { get; set; }
     }
 

The Employee class is generated in the models folder. Edit the code with the following highlighted code. I have added the Data Annotation in which I am changing the display name of the property, date property initialized & validation attribute.

 public partial class Employee
     {
         public int Id { get; set; }
         [Required(ErrorMessage="Need to provide name")]
         public string Name { get; set; }
         public string Address { get; set; }
  [Display(Name = "DateOfBirth")]
         [DataType(DataType.Date)]
         public string DOB { get; set; 
       }
     }
 

In the code above, I’ve added the Data Annotation in which I am changing the display name of the property and date property initialized.

To enable the validation need to run the following command from package manager console

PM > Install-Package jQuery.Validation.Unobtrusive

Now we will be adding the Controller & Views to perform the CURD operations

Here is my Controller code:

 public class HomeController : Controller
     {
         EmployeeModelContainer db = new EmployeeModelContainer();
         
         public ActionResult Index()
         {
             return View(db.Employees);
         }
 
         public ActionResult Details(int id)
         {
             return View();
         }
 
         
         public ActionResult Create()
         {
             return View();
         }
 
         
         [HttpPost]
         public ActionResult Create(Employee emp)
         {
             try
             {
                 // TODO: Add insert logic here
                 db.Employees.Add(emp);
                 db.SaveChanges();
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
 
         
         public ActionResult Edit(int id)
         {
             return View(db.Employees.Find(id));
         }
 
         [HttpPost]
         public ActionResult Edit(int id, Employee emp)
         {
             try
             {
                 // TODO: Add update logic here
                 db.Entry(emp).State = EntityState.Modified;
                 db.SaveChanges();
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
 
         public ActionResult Delete(int id)
         {
             return View(db.Employees.Find(id));
         }
 
         [HttpPost]
         public ActionResult Delete(int id, Employee emp)
         {
             try
             {
                 // TODO: Add delete logic here
                 db.Entry(emp).State = EntityState.Deleted;
                 db.SaveChanges();
 
 
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
     }
 

Index view code:

 @model IEnumerable<EntityFrameworkDemo.Models.Employee>
 @{
     ViewBag.Title = "Index";
 }
 
 <h2>Index</h2>
 <p>
     @Html.ActionLink("Create New", "Create")
 </p>
 <table border="1" width="50%">
     <tr>
         <th width="40%"></th>
         <th width="20%">
             Name
         </th>
         <th width="20%">
             Address
         </th>
         <th width="20%">
             DOB
         </th>
     </tr>
 
 @foreach (var item in Model) {
     <tr>
         <td>
             @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
             @Html.ActionLink("Delete", "Delete", new { id=item.Id })
         </td>
         <td>
             @item.Name
         </td>
         <td>
             @item.Address
         </td>
         <td>
             @item.DOB
         </td>
     </tr>
 }
 
 </table>
 
 
 Edit view code:
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Edit";
 }
 
 <h2>Edit</h2>
 
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
 
 @using (Html.BeginForm()) {
     @Html.ValidationSummary(true)
     <fieldset>
         <legend>Employee</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.Address)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.Address)
             @Html.ValidationMessageFor(model => model.Address)
         </div>
 
         <div class="editor-label">
             @Html.LabelFor(model => model.DOB)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.DOB)
             @Html.ValidationMessageFor(model => model.DOB)
         </div>
 
         <p>
             <input type="submit" value="Save" />
         </p>
     </fieldset>
 }
 
 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>
 
 Delete view code: 
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Delete";
 }
 
 <h2>Delete</h2>
 <h3>Are you sure you want to delete this?</h3>
 <fieldset>
     <legend>Employee</legend>
 
     <div class="display-label">Name</div>
     <div class="display-field">@Model.Name</div>
 
     <div class="display-label">Address</div>
     <div class="display-field">@Model.Address</div>
 </fieldset>
 @using (Html.BeginForm()) {
     <p>
         <input type="submit" value="Delete" /> |
         @Html.ActionLink("Back to List", "Index")
     </p>
 }
 
 
 Create view code:
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Create";
 }
 
 
 <h2>Create</h2>
 <script src="~/Scripts/jquery-1.4.1.min.js"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
 
 @using (Html.BeginForm()) {
     @Html.ValidationSummary(true)
     <fieldset>
         <legend>Employee</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.Address)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.Address)
             @Html.ValidationMessageFor(model => model.Address)
         </div>
 
         <div class="editor-label">
             @Html.LabelFor(model => model.DOB)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.DOB)
             @Html.ValidationMessageFor(model => model.DOB)
         </div>
 
         <p>
             <input type="submit" value="Create" />
         </p>
     </fieldset>
 }
 
 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>
 
 

Build & run the solution, the output will be looking like:

clip_image018

Create view output:

clip_image020

Edit view output:

clip_image022

Delete view output:

clip_image024

To add primary/foreign key association we need to delete the employee model and create it freshly & then add the association

clip_image026

Right click on Department enitity & select the option : generate the datbase from model

It will generate the script & exeute the script in database, it will create both the tables with proper relationship

clip_image028

In my next article I will be explaining you the details implementation on Entity framework Database first approach.

Happy Coding

Tarun Kumar Chatterjee

Category : .Net

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Leave a comment