How To Do Crud Operations In Entity Framework Core

The purpose of this blog is to provide an overview of Crud Operations In Entity Framework Core (Create, Read, Update, Delete).

To add logging to EF Core, follow these steps:

CRUD Implementation is the next step. First, configure the logging feature, since it functions as a profiler for monitoring EF Core’s SQL script.  It is configured in the DbContext class for demonstration purposes.

The following code needs to be added to AppDbContext.cs in EFCoreDemo.Data.

public static readonly ILoggerFactory ConsoleLoggerFactory = LoggerFactory.Create(builder =>
        {
            builder
            .AddFilter((category, level) =>
                category == DbLoggerCategory.Database.Command.Name
                && level == LogLevel.Information)
             .AddConsole();
        });  

Add the following reference package information to the project file.

<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.3"/> 

This package provides the console for displaying logs. It is referenced by Microsoft.Extensions.Logging.Console.

1. Create:

An object is added to an entity class using the Add() DbSet method

DBContext’s SaveChanges() method saves changes to the database.  The database is modified based on updates in EFCore’s track of the context.

     public static void AddUser()
        {
            var user = new User { Name = "Govind" };
            context.Users.Add(user); 
            context.SaveChanges();// Saves all changes made in this context to the database
        }

  By inserting the above code into the database, a new User object will be created.

Crud Operations In Entity Framework Core

To insert a record in the database, the Insert command produced by EFCore is shown above.

2. Read:

EFCore makes it easy to read tables.

context.Users.ToList()

Users are retrieved as a list of objects from the context using the ToList() LINQ method.

public static void GetUsers()
        {                    
            var users = context.Users.ToList();
            foreach (var user in users)
            {
                Console.WriteLine(user.Name);
            }           
    }
Crud Operations In Entity Framework Core

The above figure shows a select SQL query generated to retrieve the Users record from the database, which appears beneath the query in the Console window.

3. Update:

To update an object in the context, use the Update() method of the DbSet class. It is not always necessary to use update() every time the object is modified, since it will be tracked under the context.

public static void UpdateUser()
        {
            var user = context.Users.Find(2);
            user.Name += " Kumar";           
            context.SaveChanges();
    }

The user object is retrieved using the Find() method, and the context is used to track changes to the user object, and finally the SaveChanges() method updates the database with the changes made to the user object.  By using this method, the update can be performed without using Update().

Crud Operations In Entity Framework Core

The update command shown above is generated by EFCore.

Using Update()

public static void UpdateUser()
        {
            var user = context.Users.Find(2);
            user.Name += " Kumar";
            context.Users.Update(user);
            context.SaveChanges();
   }

Using the Update() DbSet method in the above code, the context was updated.

Batch Update

EFCore will perform a batch update if there are more than four items that need to be updated.

     public static void BatchUpdateUser()
        {
            var users = context.Users.ToList();
            users.ForEach(s => s.Name += "kumar");            
            context.SaveChanges();
        }

Because this is a batch operation, there is only one database call.

4. Remove:

A DbSet object is removed from the context of a database by using the Remove() method of the DbSet class.

      public static void RemoveUser()
        {
            var user = context.Users.Find(5);
            context.Users.Remove(user);
            context.SaveChanges();
        }

This method removes the User object with the Id =5 from the context by using the Remove() DbSet Method to remove the object from the context. Using the Find() method, the object is obtained from the entity. A change in context will be used to update the database via the SaveChanges() method.

Here is an example of a database call that was made to fetch a user from the table and to remove him from the table. This is shown in the image above.

Final thoughts:

There are some examples using simple objects to demonstrate the CRUD operations provided by Entity Framework Core.

Leave a Comment