Home > DeveloperSection > Beginner > CRUD Operations Using Entity Framework Code-First Approach

CRUD Operations Using Entity Framework Code-First Approach


ASP.Net ASP.NET MVC  Mvc4  Code First  Entity Framework 
Ratings:
0 Comment(s)
 7259  View(s)
Rate this:

CRUD Operations Using Entity Framework Code-First Approach

Hi everyone in this article I’m explaining about CRUD operations Using Entity Framework code first approach.

Introduction:

We are familiar with “Creating DB first” when we see all the tutorials on Entity Framework on the web. But in big projects where concurrency is involved and for other security reasons we really don't rely on the DB first approach. EDMX is an XML file and as a mal-user anybody can change the edmx file and the code at the end will not work. So, it's always better to use the Entity Framework Code-First approach using the Fluent API.

Description:

The ADO.NET Entity Framework is an Object Relational Mapper (ORM) included with the .NET Framework. It basically generates business objects and entities depending on the database tables. It provides basic CRUD operations, easily managing relationships among entities with the ability to have an inheritance relationship among entities. When using the EF we interact with an entity model instead of the application's relational database model. This abstraction allows us to focus on business behavior and the relationships among entities. We use the Entity Framework data context to do queries. When one of the CRUD operations is invoked, the Entity Framework will generate the necessary SQL to do the operation.

What is the Entity framework?

The Entity framework is an object-relation mapper, means - it takes the structure of the database and turns it into objects that the .Net framework can understand. Developers use those object to interact with the database instead of interacting with database directly. It’s possible to perform the full set of Create, Read, Update, and Delete (CRUD) operations using the Entity Framework features.

It has three work flows

1.       Code-first

2.       Model-first

3.       Database-first

Choosing and using the right approach can save developers a lot of time and effort, especially when interacting with complex database design.

In this Article we will work through the Code-first work flow with simple Demo Application.

What is CF?

Whether you have your relational database is in place or not, you can always define your own model classes and their properties. The beauty of this approach is there are no specified configuration files to store the DB schema and no mapping. The mapping will be generated at runtime. Also, there is no mapping to Stored Procedures. I will show later how you can call Store Procedures in the CF approach in the next article.

Step 1: Open visual studio >> File >> New Project >> ASP.NET MVC 4 Web Application

Give the application name and click ok.

After click ok a window open and you select project type.

In this sample I have select Empty.

Now our project create successfully.

Step 2: In this step I have install entity frame work from Manage NuGet Packages.

 

Step 3: Now we have create model inside Model folder.

In this figure Teacher.cs and Student.cs is treat as model but SchoolContext.cs is treat as DBContext class.

 

Teacher.cs:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Web;

 

namespace CrudOperationsCFA.Models

{

    public class Teacher

    {

        public int TeacherId { get; set; }

        public string TeacherName { get; set; }

        public string Address { get; set; }

        public ICollection<Student> Students { get; set; }

    }

}

 

Student.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace CrudOperationsCFA.Models

{

    public class Student

    {

        public int StudentId { get; set; }

        public string Name { get; set; }

        public string Class { get; set; }

        public int TeacherId { get; set; }

        public Teacher Teacher { get; set; }

    }

}

 

Step 4: Now we will create database connection in web.config file like this.

<connectionStrings>

    <add name="DBConnection" connectionString="data source=MSCLIENT-006;initial catalog=MyDB;user id=sa;password=mindstick;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

  </connectionStrings>

 

Step 5: We will now create our DBContext class. For the code-first approach we need to inherit from the DBContext base class .(note that the connection string is passed through the constructor):

SchoolContext.cs:

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace CrudOperationsCFA.Models

{

    public class SchoolContext : DbContext

    {

        public SchoolContext()

            : base("name=DBConnection")

        {

 

        }

        public DbSet<Teacher> Teacher { get; set; }

        public DbSet<Student> Students { get; set; }

 

    }

}

 

This DbModelBuilder class maps POCO classes to the database schema. This method is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuidler, but this can seriously degrade performance. More control over caching is provided through use of the DbModelBuilder and DbContext classes directly.

Step 6: Create Controller for Crud Operation

HomeController:

 

using CrudOperationsCFA.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace CrudOperationsCFA.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

 

        public ActionResult Index()

        {

            return View();

        }

    }

}

 

 

Index.Cshtml:

@{

    ViewBag.Title = "Index";

}

 

@Html.ActionLink("Teacher","Index","Teacher")

@Html.ActionLink("Student","Index","Student")

TeacherController:

using CrudOperationsCFA.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace CrudOperationsCFA.Controllers

{

    public class TeacherController : Controller

    {

        //

        // GET: /Teacher/

 

        SchoolContext context;

 

        public TeacherController()

        {

            context = new SchoolContext();

        }

        public ActionResult Index()

        {

            var teacher = context.Teacher.ToList();

           

            return View(teacher);

        }

        public ActionResult Add()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Add(Teacher model)

        {

            if (ModelState.IsValid)

            {

                context.Teacher.Add(model);

                context.SaveChanges();

            }

            return RedirectToAction("Index","Teacher");

        }

 

        public ActionResult Update(int id)

        {

            return View(context.Teacher.Find(id));

        }

 

        [HttpPost]

        public ActionResult Update(Teacher model)

        {

            Teacher teacher = context.Teacher.Where(m=>m.TeacherId==model.TeacherId).SingleOrDefault();

            if (teacher!=null)

            {

                context.Entry(teacher).CurrentValues.SetValues(model);

                context.SaveChanges();

                return RedirectToAction("Index", "Teacher");

            }

            return View(model);

        }

 

        public ActionResult Delete(int id)

        {

            context.Teacher.Remove(context.Teacher.Find(id));

            context.SaveChanges();

            return RedirectToAction("Index", "Teacher");

        }

    }

}

 

Index.cshtml:

@model IList<CrudOperationsCFA.Models.Teacher>

@{

    ViewBag.Title = "Index";

}

<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">

    <h2 class="text-center text-primary">Teacher Details</h2>

    <div class="table-responsive">

        <table class="table table-bordered table-striped">

            <thead>

                <tr>

                    <td>ID</td>

                    <td>Teacher Name</td>

                    <td>Address</td>

                    <td>Update</td>

                    <td>Delete</td>

                </tr>

            </thead>

            @foreach (var item in Model)

            {

                <tr>

                    <td>@item.TeacherId</td>

                    <td>@item.TeacherName</td>

                    <td>@item.Address</td>

                    <td>@Html.ActionLink("Update", "Update", "Teacher", new { id=@item.TeacherId}, null)</td>

                    <td>@Html.ActionLink("Delete", "Delete", "Teacher", new { id = @item.TeacherId }, null)</td>

                </tr>

            }

        </table>

    </div>

 

    @Html.ActionLink("New Teacher", "Add", "Teacher", new { @class="btn btn-primary"})

    @Html.ActionLink("Student", "Index", "Student", new { @class="btn btn-primary"})

</div>

 

 

Add.cshtml:

@model CrudOperationsCFA.Models.Teacher

@{

    ViewBag.Title = "Add";

}

 

<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

 

<div class="container">

    <h2 class="text-center text-primary">New Teacher</h2>

    <div class="table-responsive">

        <table class="table table-bordered table-striped">

            @using (Html.BeginForm("Add", "Teacher", FormMethod.Post))

            {

                <tr>

                    <td>Name</td>

                    <td>@Html.TextBoxFor(m => m.TeacherName)</td>

                </tr>

                <tr>

                    <td>Address</td>

                    <td>@Html.TextBoxFor(m => m.Address)</td>

                </tr>

                <tr>

                    <td>

                        <input type="submit" value="Save" /></td>

                </tr>

            }

        </table>

    </div>

 

</div>

 

Update.cshtml:

@model CrudOperationsCFA.Models.Teacher

@{

    ViewBag.Title = "Update";

}

 

 

<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

 

<div class="container">

    <h2 class="text-center text-primary">Update</h2>

    <div class="table-responsive">

        <table class="table table-bordered table-striped">

            @using (Html.BeginForm("Update", "Teacher", FormMethod.Post))

            {

                @Html.HiddenFor(x=>x.TeacherId)

                <tr>

                    <td>Name</td>

                    <td>@Html.TextBoxFor(m => m.TeacherName)</td>

                </tr>

                <tr>

                    <td>Address</td>

                    <td>@Html.TextBoxFor(m => m.Address)</td>

                </tr>

                <tr>

                    <td colspan="2" class="text-right">

                        <input type="submit" value="Save" class="btn btn-primary" /></td>

                </tr>

            }

        </table>

    </div>

</div>

 

 

 

Similarly we create controller for student and perform crude operation as state in teacher module.


Don't want to miss updates? Please click the below button!

Follow MindStick