bulk insert using EntityFramework-Plus


Question

I was planning to use EntityFramework-Plus for bulk operations however i am not sure if it supports bulk insert.

So for example, i have Parent entities and i want to insert Child entities in bulk how do i dot that using EF Plus

In code below number of parents could be between 1000-2000 range and number of children are 10-20. I want to add same children for each parent, if condition satisfies

public async Task AddChildern(IEnumerable<Child> children)
{
    var ids =  GetIDs();
    var result = _dbContext.Parent.Where(x=> ids.contains(x.ID)).ToListAsync();
   foreach(var p in result)
   {
         foreach(var child in children)
         {
               var flag = CanAddChild(child);
               if(flag)
               {
                    p.Children.Add(child);
               }
         }
   }
}

Expert Answer

Disclaimer: I'm the owner of the project Entity Framework Plus

This library doesn't support BulkInsert.

Disclaimer: I'm the owner of the project Entity Framework Extensions

This library supports BulkInsert but it's not free.

(EF Plus is powered by this library)

In your scenario, since it looks child entity doesn't have a direct relation to the parent (No navigation property or parent ID), you should use the BulkSaveChanges method.

public async Task AddChildern(IEnumerable<Child> children)
{
    var ids =  GetIDs();
    var result = _dbContext.Parent.Where(x=> ids.contains(x.ID)).ToListAsync();
    foreach(var p in result)
    {
         foreach(var child in children)
         {
               var flag = CanAddChild(child);
               if(flag)
               {
                    p.Children.Add(child);
               }
         }
    }
}

// ...code... 

_dbContext.BulkSaveChanges();

EDIT: Answer Comment

Child does have ParentID

Depending on how the relation is set, you could also do a direct BulkInsert.

_dbContext.BulkInsert(result.SelectMany(x => x.Children));




Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why