title: What are the steps and tools used to troubleshoot Entity Framework performance problems?
body: <p>I'm looking at an existing system that has a significant performance problem when inserting data using LINQ to Entities. The relationships are complex.</p>
  
  <p>I am familiar with common Entity Framework performance factors such as how often SaveChanges is called, etc. There are two problems with this, though. First, it's not the problem here (the performance problem occurs before SaveChanges even happens). Second, it's just guessing. It often works but it's not a process, it's a hope.</p>
  
  <p>I'd like to know the best way to deal with these big problems the real way, where hope doesn't work. If this were ADO using SQL commands, the tool would be SQL Server Performance Profiler to see how many queries were happening, what they were, what their execution plans are, etc., and then adjusting the commands to mitigate those problems. In Entity Framework land, these tools aren't effective because there is not a 1-1 mapping between what you tell it and the commands it generates, and in this particular case it's not even SQL being slow.</p>
  
  <p>Although I'd like the answer here to be a generic approach, here is the relevant code specific to my current problem:</p>
  
  <pre><code>    foreach( var thing in objectsToImport ) {
        var newEntityFrameworkManagedObject = new EntityFrameworkManagedObject { createdOn = DateTime.UtcNow };
        newEntityFrameworkManagedObject.OtherExistingEntity = getExistingEntity( thing.OtherEntityMatchingInfo );
        ... /*Many more lines associating new object to a bunch of existing items selected before loop.*/
        modelRepository.Insert( newEntityFrameworkManagedObject );
      }
      ...
      modelRepository.SaveChanges();
  </code></pre>
  
  <p>The performance hit is on modelRepository.Insert(). We're importing a CSV of several-hundred rows and each call to Insert takes a full minute. Notice that it never gets to SaveChanges. Even the first item to be inserted is slow.</p>