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:
1 |
ctx.Database.Log = x => System.Diagnostics.Debug.WriteLine(x); |
The log in Output window shows that Entity Framework generates the same sequence of T-SQL commands.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Opened connection at 19.09.2016 19:23:34 +03:00 Started transaction at 19.09.2016 19:23:34 +03:00 INSERT [dbo].[Clients]([Name], [CountryCode]) VALUES (@0, NULL) SELECT [Id], [Timestamp] FROM [dbo].[Clients] WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity() -- @0: 'Jeff' (Type = String, Size = 50) -- Executing at 19.09.2016 19:23:35 +03:00 -- Completed in 1 ms with result: SqlDataReader INSERT [dbo].[Clients]([Name], [CountryCode]) VALUES (@0, NULL) ... Committed transaction at 19.09.2016 19:23:35 +03:00 Closed connection at 19.09.2016 19:23:35 +03:00 |
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.