Friday, 1 November 2024

What is the difference between Add() and AddRange() methods in EF Core?

In Entity Framework Core (EF Core), both Add() and AddRange() methods are used to insert data into the database, but they differ in how they handle multiple entities and their performance:

1. Add() Method

  • Purpose: Adds a single entity to the context, marking it as "Added." This means EF Core will track it and include it in the next SaveChanges() call to insert it into the database.

  • Usage: Use Add() when you need to add a single entity.

  • Example:


    using (var context = new AppDbContext()) { var product = new Product { Name = "Laptop", Price = 1200.00m }; context.Products.Add(product); context.SaveChanges(); // Saves one entry to the database }

2. AddRange() Method

  • Purpose: Adds multiple entities to the context at once. All entities are marked as "Added" and will be inserted into the database during the next SaveChanges() call.

  • Usage: Use AddRange() when you have a list or collection of entities to add.

  • Performance: AddRange() is generally more efficient than calling Add() multiple times in a loop because it reduces the overhead of multiple method calls.

  • Example:


    using (var context = new AppDbContext()) { var products = new List<Product> { new Product { Name = "Laptop", Price = 1200.00m }, new Product { Name = "Smartphone", Price = 800.00m }, new Product { Name = "Tablet", Price = 400.00m } }; context.Products.AddRange(products); context.SaveChanges(); // Saves multiple entries in a single batch }

Key Differences

FeatureAdd()AddRange()
PurposeAdds a single entityAdds multiple entities
ParameterSingle entity objectCollection of entities
PerformanceSuitable for single insertMore efficient for batch inserts
Usage ScenarioAdding one entity at a timeAdding multiple entities simultaneously

Summary

  • Use Add() when you have one entity to add.
  • Use AddRange() when you have multiple entities to add, as it is more efficient for batch inserts.
Share:

0 comments:

Post a Comment