In Entity Framework, data insertion is one of the basic and most common CRUD operations that 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 taken in the database yet.
When you want to perform the data in 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: It is the instance of the
DbContext
class that represents the session with the database. - Entity: It is the name of the
DbSet
that represents the table in the database. - entity: It is the object you want to insert.
Suppose we have a 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
Product
with the desired data. - We use
Add
to add the product to the context. - We call
SaveChanges
to execute the insertion in the database.
Multiple Insertion with AddRange
The AddRange
method is an extension of Add
that allows you to insert 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 calls to the database and improves performance.
dbContext.Entity.AddRange(entities);
Where:
entities
: It is a collection of objects that 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
AddRange
to add all the products to the context. - We call
SaveChanges
to execute the insertions in the database.
When inserting multiple records in a single operation, the number of queries to the database is reduced.
But it is not a bulk operation. That is, it is still relatively slow.