Code and prod logo

Code and Prod Complet Projects

Follow me

EL JIHAOUI
QUICK ACCESS

Insert data using DbSet and DbContext

Insert data using DbSet and DbContext

Table of Contents

Insert Data using Entity Framework core

In this tutorial, we will discuss two methods that allow us to insert data into a database, so we will see how we can use Entity Framework core to Insert data via DbSet and how to Insert data via the DbContext.

Insert data using DbSet

It’s very easy to use Entity Framework Core (EF Core) to perform insert operations and save Data into the database. in this case, we can use DbSet class that represents an entity set that can be used for CreateReadUpdate, and Delete operations (CRUD Operations).

In our Project, AppDbContext class (derived from DbContext) must include the DbSet type properties for the entities which map to database tables and views.

DbSet class contains a function “Add” which can be used to add the given entity to the context with the Added state. When the changes are saved using BbContext.SaveCahnages().

The entities in the Added states are inserted into the database. After the changes are saved, the object state changes to Unchanged.

Example: BbContext.Books.Add(Book)

To add this object Book “{ Name = “CSharp”, Description = “Programming with C#” }” in the database using DbSet, we can do it this way, in the Program.cs file we need to add the following code (see this article Visual Studio Code):

				
					AppDbContext db = new();
Book b = new() { Name = "CSharp", Description = "Programming with C#" };
if (db != null)
{
    db.Books?.Add(b);
    bool res = (await db.SaveChangesAsync()) > 0;
    if(res){
        WriteLine("Book Inserted successfully");
    }else{
        WriteLine("Book not Inserted successfully");
    }
}
				
			

When we add the entity in the Books entity Set, it’s obligatory to call DbContext.SavaChanges() or await DbContext.SaveChangesAsync() in asynchronous approach programming to commit all the changes to the Database

Insert data using DbContext

We can do the same operation using the DbContext directly using the Add function associated with the DbContext like this :

				
					AppDbContext db = new();
if (db != null)
{
    Book b = new() { Name = "CSharp", Description = "Programming with C#" };
    db.Add<Book>(b); // or  db.Add(b)
    bool res = (await db.SaveChangesAsync()) > 0;
    if(res){
        WriteLine("Book Inserted successfully");
    }else{
        WriteLine("Book not Inserted successfully");
    }
}
				
			

NB: when we add the data with the Add method, the data is stored in the collection but in memory, we must call the SaveChanges() method of dbContext to commit and store the data in the database.

DbContext.SaveChanges(): Saves all changes made in this context to the underlying database. Returns(Int32) the number of state entries written to the database

DbContext.SaveChangesAsync()Asynchronously saves all changes made in this context to the underlying database. Returns (Task<Int32>) a task that represents the asynchronous save operation. The task result contains the number of state entries written to the database.

Course video

if you like it share it please

Facebook
LinkedIn
Twitter
Related Posts
Data Seeding in migration using EF Core
Entity Framework Core
EL JIHAOUI

Data seeding

Data seeding is a process where you populate a database with an initial set of data
There are

Read More »

MORE RESSOURCES