Inserting Into Entity Framework. Add() vs AddRange()

Entity Framework offers two methods to insert records into database. Add() method allows to insert a single entity. AddRange() method inserts an IEnumerable collection. The main question is does the second method provide any benefit over the first one?

The most important is the database performance. I’ve created a simple test where I added single records with Add() method and a List with AddRange(). I called SaveChanges() after each block.

Also I’ve enabled context database logging with the following command:

The log in Output window shows that Entity Framework generates the same sequence of T-SQL commands.

Yeah, EF generates single INSERT command per each record. So the only benefit is the ease of writing C# code, but you’ll never get any gain from database.
[UPDATE 2016-09-22]
One benefit is the ease of writing C# code. Another is some internal EF optimization in working with ChangeTracking. As stated in MSDN article Performance Considerations for Entity Framework 4, 5, and 6 “the advantage of using the range methods is that the cost of DetectChanges is only paid once for the entire set of entities as opposed to once per each added entity”. But from the database perspective it won’t give you any gain.

Leave a Reply

Your email address will not be published. Required fields are marked *