Loading

Microsoft Entity Framework

How to perform CRUD Operations in Entity Framework Database First Approach?. The Complete Microsoft Entity Framework Developer Course 2022 [Videos].

In this Video, I am going to discuss how to perform CRUD Operations in Entity Framework Database First Approach. Please watch our previous Video where we discussed the Relationships Between Entities in Entity Framework.

Note: We are going to work with the same example that we created in our Introduction to Entity Framework Database First VideoPlease watch our introduction to Entity Framework Database First Video before proceeding to this Video.

CRUD Operations in Entity Framework:

CRUD Operation means we need to perform Create, Update, Delete, and Retrieve Operations. In order to perform the Insert, Update, and Delete operations in Entity Framework we have two persistence scenarios i.e. connected and disconnected.

In the connected scenario, the same DbContext instance is used for retrieving and saving the entities, whereas this is different in the disconnected scenario. In this Video, we will learn about saving data in the connected scenario, and in our upcoming Videos, we will discuss how to perform the CRUD Operations in a disconnected scenario.

An entity that contains data in its scalar property will be either inserted, updated, or deleted, based on its EntityState. The Entity Framework builds and executes the INSERT, UPDATE, and DELETE SQL statements for the entities whose EntityState is Added, Modified, and Deleted respectively when the SaveChanges() method is called on the DbContext instance. The following diagram shows the CUD (Create, Update, Delete) operations in the connected scenario.

CRUD Operations in Entity Framework Database First Approach

Note: In the connected scenario, an instance of DbContext class keeps track of all the entities and when an entity is created, modified, or deleted, it automatically sets the appropriate EntityState to the entity.

Create Operation:

Create Operation means we need to add a new object. Adding a new object using the Entity Framework is very simple. First, you need to create an instance of the entity which you want to add to the database. Once you created the instance of the entity then you need to the Add method of DbSet and pass the entity. Finally, call the SaveChanges method on the DbContext instance which will insert the new record in the database. The following code lets you add a new student to the database.

namespace DBFirstApproach
{
class Program
{
static void Main(string[] args)
{
//Create a new student
var newStudent = new Student()
{
FirstName = "Dotnet",
LastName = "Tutorials",
StandardId = 1
};
//Create DBContext object
using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
{
//Add Student object into Students DBset
context.Students.Add(newStudent);
// call SaveChanges method to save student into database
context.SaveChanges();
}
}
}
}

In the above example, context.Students.Add(newStudent) adds the newly created student instance to the context object with Added EntityState and when the context.SaveChanges() method is called, it builds and executes the following INSERT statement to the database. We have captured the following script using SQL Server Profiler tools.

Create Operation in Entity Framework Database First Approach

Update Operation:

As we alwatchy discussed in the connected scenario, the Entity Framework keeps track of all the entities retrieved using the context. Therefore, when we edit any entity data, the Entity Framework will automatically mark the EntityState as Modified and when the SaveChanges method is called, it updates the updated data into the underlying database. The following code is used to change the first name and last name of the student whose id is 3.

using System.Linq;
namespace DBFirstApproach
{
class Program
{
static void Main(string[] args)
{
//Create DBContext object
using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
{
//Retrieve the student whose id is 3
var student = context.Students.FirstOrDefault(x => x.StudentId == 3);
//update the first name and last name
student.FirstName = "Ram";
student.LastName = "Sharma";
// call SaveChanges method to save student into database
context.SaveChanges();
}
}
}
}

In the above example, first, we retrieve the student from the database using the LINQ query. As soon as we modify the FirstName and LastName, the context sets its EntityState to Modified and when we call the SaveChanges() method, it builds and executes the following Update statement in the database.

Update Operation in Entity Framework Database First Approach

Delete Operation:

To delete an entity using Entity Framework, we need to use the Remove method on DbSet. The DbSet Remove works for both existing and newly added entities. When you call the Remove method on an entity that has been added but not yet saved to the database will cancel the addition of the entity. The following code shows we added one entity in the context but not call the SaveChanges method and then we call the Remove method. In this case, the entity is removed from the change tracker and is no longer tracked by the DbContext.

namespace DBFirstApproach
{
class Program
{
static void Main(string[] args)
{
var newStudent = new Student()
{
FirstName = "Test1",
LastName = "Test2",
StandardId = 1
};
using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
{
context.Students.Add(newStudent);
context.Students.Remove(newStudent);
}
}
}
}

Calling the Remove method on an existing entity that is being change-tracked will register the entity for deletion the next time SaveChanges is called. The following example is of a code where the student is removed from the database whose StudentId is 6.

using System.Linq;
namespace DBFirstApproach
{
class Program
{
static void Main(string[] args)
{
using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
{
var student = context.Students.FirstOrDefault(x => x.StudentId == 6);
context.Students.Remove(student);
context.SaveChanges();
}
}
}
}

In the above example, context.Students.Remove(student) marks the student entity object as Deleted and when we call the SaveChanges method on the Context object, the Entity Framework will build and execute the following DELETE statement in the database.

Delete Operation in Entity Framework Database First Approach

Read Operation:

Reading existing data from the database is very simple. In the below example, we are retrieving all the records from the Student table and then displaying the FirstName and LastName in the Console window.

using System;
using System.Linq;
namespace DBFirstApproach
{
class Program
{
static void Main(string[] args)
{
using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
{
var AllStudents = context.Students.ToList();
foreach(var student in AllStudents)
{
Console.WriteLine($"FirstName : {student.FirstName} LastName : {student.LastName}");
}
Console.Read();
}
}
}
}
Output:

Read Operation in Entity Framework Database First Approach

When we execute the above program, it generates the following SQL Script.

CRUD Operations using Entity Framework Database First Approach

See All

Comments (442 Comments)

Submit Your Comment

See All Posts

Related Posts

Microsoft Entity Framework / Blog

What is the Entity Framework?

Entity Framework is an Open-Source Object-Relational Mapping (ORM) Framework for .NET applications that enables .NET developers to work with relational data using domain-specific objects without focusing on the underlying database tables and columns where actually the data is stored. That means the Entity Framework eliminates the need for writing the data-access code that developers usually need to write.
11-Feb-2022 /37 /442

Microsoft Entity Framework / Blog

What is Entity Framework Architecture?

In this article, I am going to discuss the Entity Framework Architecture in Detail. Please read our previous article where we discussed the Overview of the Entity Framework. At the end of this article, you will understand the following pointers in detail.
11-Feb-2022 /37 /442

Microsoft Entity Framework / Blog

What is Context Class in Entity Framework?

In this article, I am going to discuss the Entity Framework Context Class with an example. Please read our previous article where we discussed the Architecture of Entity Framework in Detail. At the end of this article, you will understand what exactly the Context Class is and when and how to use this Context Class in Entity Framework with an example.
11-Feb-2022 /37 /442