EF Insert entity with large number of new child entities

c# entity-framework entity-framework-6

Question

I've seen a number of "Bulk Insert in EF" questions however all of these deal with a usecase where a user is trying to insert a large array of items.

I've a situation where I have a new Parent entity with ~1500 new related entities attached to it. Both the parent and the child entities are mapped to their own tables in EF.

At the moment I'm using something like:

//p is already created and contains all the new child items    
public void SaveBigThing(Parent p){
  if(p.Id == 0){
    // we've got a new object to add
    db.BigObjects.Add(p);
  }
  db.SaveChanges();
}

Entity Framework at the moment creates an individual insert statement for each and every child item. Which takes 50 seconds or so. I want to be able to use db.ChildEntity.AddRange(items) But I'm unsure if there's a better way than to use 2 separate operations. First create the parent to get it's Id then a AddRange for all the child items?

1
1
1/5/2016 1:06:41 PM

Popular Answer

IMHO You dont need to add parent first in-order to insert child items. You could do that in one shot.

You could try this in EF 5 AddRange is only available in EF 6 or higher.

This will not insert the item in bulk it will generate the query and insert at one shot

Ef bulk insertion reference

Another reference

public bool InsertParent(Parent parentObject)
{   
    //Assuming this is the parent table
    db.BigObjects.Add(parentObject);
    InsertChilds(parentObject); //Insert childs
    db.SaveChanges();
}

public bool InsertChilds(Parent parentObject)
{
    // This will save more time . 
    DataContext).Configuration.AutoDetectChangesEnabled = false;
    foreach(var child in parentObject.Childs)
    {
        //This will set the child parent relation
        child.Parent = childParent;
        db.ChildEntity.Add(child);
    }
    DataContext).Configuration.AutoDetectChangesEnabled = true;

}
0
5/23/2017 11:59:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow