In Entity Framework, data insertion is one of the basic and most common CRUD operations we will perform in an application.
Inserting data involves adding new entities to the database. For this, in Entity Framework we mainly have two methods: Add and AddRange.
When you insert an entity into the DbContext, it will be added with the Added state, but no actions will be performed on the database yet.
When you want to apply the changes to the database, we execute SaveChanges. Then the corresponding SQL statement (INSERT) will be generated and persisted in the database.
Simple Insertion with Add
The Add method is the most basic way to insert an entity into the database. This method adds a single entity to the EF context.
dbContext.Entity.Add(entity);
Where:
- dbContext: Is the instance of the
DbContextclass that represents the session with the database. - Entity: Is the name of the
DbSetthat represents the table in the database. - entity: Is the object you want to insert.
Suppose we have a Product (Product) entity that represents a table in the database:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
To insert a new product, we would do the following:
using (var context = new MyDbContext())
{
var newProduct = new Product
{
Name = "Laptop",
Price = 1200.00m
};
context.Products.Add(newProduct); // We add the product to the context
context.SaveChanges(); // We persist the changes to the database
}
In this example:
- We create an instance of
Productwith the desired data. - We use
Addto add the product to the context. - We call
SaveChangesto execute the insertion in the database.
Multiple Insertion with AddRange
The AddRange method is an extension of Add that allows inserting multiple entities in a single operation.
This is useful when you need to add a large number of records, as it reduces the number of database calls and improves performance.
dbContext.Entity.AddRange(entities);
Where:
entities: Is a collection of objects you want to insert.
Continuing with the Product example, suppose we want to insert several products at once:
using (var context = new MyDbContext())
{
var products = new List<Product>
{
new Product { Name = "Keyboard", Price = 50.00m },
new Product { Name = "Mouse", Price = 25.00m },
new Product { Name = "Monitor", Price = 300.00m }
};
context.Products.AddRange(products); // We add the list of products
context.SaveChanges(); // We persist the changes to the database
}
In this example:
- We create a list of products.
- We use
AddRangeto add all products to the context. - We call
SaveChangesto execute the insertions in the database.
When inserting multiple records in a single operation, the number of database queries is reduced.
But it is not a bulk operation. That is, it is still relatively slow.
