Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a list of entities to DbSet

DbSet.Add() adds a single Entity to DbSet. But there is no DbSet.AddRange() to add a list of entities. Is there a method I can call directly from EF that allows me to add a list of Entities? If not, is there any reason why EF does not provide such a method?

like image 324
hshen Avatar asked Feb 12 '12 01:02

hshen


2 Answers

In EF6 both DbSet.AddRange and DbSet.RemoveRange are available.

The reason to implement them is to improve the performance, what is done by disabling DetectChanges for each individual addition or removal of an entity.

More details:

  • UpForGrabs: Consider adding DbSet.AddRange API
  • UpForGrabs: Consider adding DbSet.RemoveRange API

NOTE: There isn't still official documentation for this method, as EF is still RC1.

UPDATE: EF6 has been release, and the official documentation for .AddRange() is here, but the explanation of what's happening inside it's in the links above.

like image 86
JotaBe Avatar answered Oct 25 '22 16:10

JotaBe


Eranga's comment is arguably true. I guess that the real concern is what should be done if any entity in the list has the key property set if the key for underlying table is an identity column:

  • Throw a exception? OR
  • set key to zero so a new entity with different key will be inserted? OR
  • update the entity with same key?

For this reason, it does not make too much sense to implement AddRange() to the generic class DbSet. If you want something particular fitting your need, you may extend DbSet as following

   public static class EFExtension 
   {

      public static void AddRange<TEntity>(this DbSet<TEntity> dbSet, IList<TEntity> entities) where TEntity : class
      {
        foreach (TEntity e in entities)
        {
            dbSet.Add(e);
        }
     }
  }
like image 39
hshen Avatar answered Oct 25 '22 14:10

hshen