title: EF Codefirst Bulk Insert
body: <p>I need to insert around 2500 rows using EF Code First.</p>
  
  <p>My original code looked something like this:</p>
  
  <pre><code>foreach(var item in listOfItemsToBeAdded)
  {
      //biz logic
      context.MyStuff.Add(i);
  }
  </code></pre>
  
  <p>This took a very long time. It was around 2.2 seconds for each <code>DBSet.Add()</code> call, which equates to around 90 minutes.</p>
  
  <p>I refactored the code to this:</p>
  
  <pre><code>var tempItemList = new List&lt;MyStuff&gt;();
  foreach(var item in listOfItemsToBeAdded)
  {
      //biz logic
      tempItemList.Add(item)
  }
  context.MyStuff.ToList().AddRange(tempItemList);
  </code></pre>
  
  <p>This only takes around 4 seconds to run. However, the <code>.ToList()</code> queries all the items currently in the table, which is extremely necessary and could be dangerous or even more time consuming in the long run. One workaround would be to do something like <code>context.MyStuff.Where(x=&gt;x.ID = *empty guid*).AddRange(tempItemList)</code> because then I know there will never be anything returned.</p>
  
  <p>But I'm curious if anyone else knows of an efficient way to to a bulk insert using EF Code First?</p>