title: C# : SQL Server Bulk insert poor performance (Entity Framework 5)
body: <p>I'm facing a performance issue, using c# with EF5 and a SQL Server 2012 database (with 4gb RAM), while trying to insert thousands of items.</p>
  
  <p>For example, this code took me 12s to execute in a MVC app, and 5s in a Windows console app, 99% of it consume by <code>context.saveChanges()</code> statement.</p>
  
  <pre><code>//Prepare list
          Random rand = new Random();
          List&lt;MyItem&gt; list = new List&lt;MyItem&gt;();
  
          for(int i = 0; i &lt; 1000; i++) {
              list.Add(new MyItem {
                  Field1 = i,
                  Field2 = rand.Next(1000),
                  Field3 = rand.Next(1000),
                  Field4 = rand.Next(1000),
                  Field5 = rand.Next(1000),
                  Field6 = rand.Next(1000),
                  Field7 = rand.Next(1000),
                  Field8 = rand.Next(1000),
                  Field9 = rand.Next(1000),
                  Field10 = rand.Next(1000)
              });
          }
  
  
  
          Stopwatch watch = new Stopwatch();
          Stopwatch watch2 = new Stopwatch();
  
          watch.Start();
  
          using (var context = new MyEntities())
          {
              context.Configuration.AutoDetectChangesEnabled = false;
              context.Configuration.ValidateOnSaveEnabled = false;
              foreach (MyItem item in list)
              {    
                  context.MyItem.Attach(item);
                  context.Entry(item).State = System.Data.EntityState.Added;           
              }
  
              watch2.Start();
              context.SaveChanges();
              watch2.Stop();
          }
          watch.Stop();
  </code></pre>
  
  <p>I tried to turn off AutoDetectChangesEnabled and ValidateOnSaveEnabled but it seems that there is no performance gain. I also tried with a single insert stored procedure, but the performance where similar.</p>
  
  <p>The table MyItem is a simple table with ten integer fields, one clustered primary key.</p>
  
  <p>Any help will be appreciate ! </p>