SharePoint Pals
 | Sign In
Entity Framework Model first approach to Read/Insert/Update/Delete database data in Asp.Net MVC & C#
by Tarun Kumar Chatterjee 14 May 2016
Author
.Net – Technology Specialist
Visits   
Today  :   10     Total  :    4025

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

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation