Getting Start with Entity Framework Core 3.1 – Part IV

Introduction:

In this blog you will learn about the CRUD (Create, Read, Update, Delete) operation in Entity Framework Core.

This is a continuation of my last blog.

Adding Logging to EF Core:

Before getting into the CRUD Implementation, lets configure the logging feature, because it acts as profiler to monitor the SQL script created by EF Core.  For a demo I configured it in DbContext class.

Open AppDbContext.cs file from EFCoreDemo.Data project and add below code.

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

Edit the project file by adding following reference package information.

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

The package Microsoft.Extensions.Logging.Console reference is added to include the console to display the log.

1. Create

Add() DbSet method is used to add the object to the entity class

SaveChanges() is a DBContext method.  Basically, it modifies the database based on the update in the context which is in track by EFCore.

     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
        }

   The above code will insert the new User object in database.

Figure 1: Insert Command

The above Image shows the Insert command which is generated by EFCore to insert the record in the database.

2. Read

Reading the table is super easy in EFCore.

context.Users.ToList()

The ToList() LINQ method is used to retrieve all the Users as a list of objects from the context.

public static void GetUsers()
        {                    
            var users = context.Users.ToList();
            foreach (var user in users)
            {
                Console.WriteLine(user.Name);
            }           
    }

 

Figure 2: Select Command

From the above figure you can observe the select SQL query is generated to fetch the Users record from the database and the list of records displayed underneath it in Console window.

3. Update

Update() – DbSet method is used to update the object in the context. Basically whenever the object is modified it will be under context tracking, sometime its is not necessary to use update().

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

From the above code you can observe, first the user object is fetched based on the Id key parameter using the Find() method, then we updated the user object which is tracked by the context, and finally the SaveChanges() method will be used to update the database based on the changes tracked in context.  In this way the update is done without using the Update() method.

Figure 3: Update Command

The above Image shows the update command which 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();
   }

From the above code you can observe we have used Update() DbSet method to update the context.

Batch Update

The EFCore will do a batch update if the number of updated objects is more than 4.

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

The above Image shows that there is only one call to the database, since it is batch update.

4. Remove

Remove() – DbSet method is used to remove the object from the context.

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

The User object with the Id =5 is fetched using the Find() method and passed to the Remove() DbSet Method, which removes the object from the entity in the context. Finally the SaveChanges() method will update the database based on the change in context.

Figure 5: Remove Command

The above Image shows one database call is made to fetch the user and another call to remove that user from the table

Summary:

We have seen how to perform the CRUD operation in Entity Framework Core with some examples which handles with simple objects.

Source Code – https://github.com/gowthamece/EFCore

Happy Coding!!!

gowthamk91

2 thoughts on “Getting Start with Entity Framework Core 3.1 – Part IV

Leave a Reply to arunCancel reply

Discover more from Gowtham K

Subscribe now to keep reading and get access to the full archive.

Continue reading