articles

Home / DeveloperSection / Articles / CRUD Operations Using Entity Framework Code-First Approach

CRUD Operations Using Entity Framework Code-First Approach

CRUD Operations Using Entity Framework Code-First Approach

Anonymous User29807 03-Feb-2015

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:

Where 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.

These provide basic CRUD operations, And they easily managing relationships among entities with the ability to have an inheritance relationship among entities.

In this architecture, when we using the EF we interact with an entity model instead of the application's relational database model.

Its abstraction allows us to focus on business behavior and the relationships among entities. We use the Entity Framework data context to do queries.

Whenever 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, which means - it takes the structure of the database and turns it into objects that the .Net framework can understand.

Developers use those objects to interact with the database instead of interacting with the 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 workflows

Choosing and using the right approach can save developers a lot of time and effort,

especially when interacting with complex database design.

Into this Article we will work through the Code-first workflow 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

CRUD Operations Using Entity Framework Code-First Approach

Give the application name and click ok.

After click ok, a window opens and you select project type.

CRUD Operations Using Entity Framework Code-First Approach

In this sample, I have select Empty.

Now our project creates successfully.

Step 2: In this step, I have to install an entity framework from Manage NuGet Packages.

CRUD Operations Using Entity Framework Code-First Approach

 Step 3: Now we have created a model inside the Model folder.

In this figure, Teacher.cs and Student.cs are treating as a model but SchoolContext.cs is treating as a DBContext class.

CRUD Operations Using Entity Framework Code-First Approach

 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 a database connection in the 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; }
 
    }
}

The DbModelBuilder class maps POCO classes to the database schema. These methods are called only once when the first instance of a derived context is created. A model for that context is then cached and is for all further instances of the context in the app domain. Its caching can be disabled by setting the ModelCaching property on the given ModelBuidler, but this can seriously degrade performance. Much control over the caching is provided through the 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 a controller for students and perform the crude operation as the state in the teacher module.



Updated 08-Jul-2020
I am a content writter !

Leave Comment

Comments

Liked By