title: Entity Framework initialization is SLOW -- what can I do to bootstrap it faster?
body: <p>My EF 4.3.1 model has 200-odd tables.  Initial startup is horrible, several minutes.  A DotTrace-captured profile implies some terrible algorithm/scalability choices deep in the framework, as evidenced by the millions of calls to a number of methods down there and the 36 million IEnumerable.Contains() calls.  Here is a snippet, this is all triggered by the first query done on the database (future queries don't do this and are fine).</p>
  
  <p><img src="https://i.stack.imgur.com/BzUGp.png" alt="enter image description here"></p>
  
  <p>What can I do to my model to make this less painful?  Can I precompile this somehow?  Better, can the EF team please address these issues or open source the framework so I can?  Or at least fix the spelling of <code>Warapper</code>? :)</p>
  
  <p>EDIT: One specific EF call that triggers this is basically <code>var db = new MyDbContext(); db.Personnel.Where(a =&gt; a.Login == login).SingleOrDefault();</code>.  Also an EF Migrations Seed() AddOrUpdate generates effectively the same stack.  The fuller stack trace, which may give a little more context, is here: <a href="https://i.stack.imgur.com/BH9v8.png" rel="nofollow noreferrer">Fuller Stack Trace</a></p>
  
  <p>EDIT: Some relevant links:</p>
  
  <ul>
  <li>MSDN: <a href="http://msdn.microsoft.com/en-us/library/cc853327%28v=vs.110%29.aspx" rel="nofollow noreferrer">Performance Considerations (Entity Framework)</a> (thanks to @AakashM)</li>
  <li>MSDN: <a href="http://blogs.msdn.com/b/adonet/archive/2011/05/18/ef-power-tools-ctp1-released.aspx" rel="nofollow noreferrer">EF Power Tools</a></li>
  <li>SO: <a href="https://stackoverflow.com/questions/6185918/entity-framework-4-1-for-large-number-of-tables-715">Entity Framework 4.1 for large number of tables (715)</a></li>
  </ul>
  
  <p>EDIT2: Now that they just <a href="http://entityframework.codeplex.com/" rel="nofollow noreferrer">open sourced</a> the code, it appears that this line:</p>
  
  <pre><code>//Filter the 1:1 foreign key associations to the ones relating the sets used in these cell wrappers.
  oneToOneForeignKeyAssociationsForThisWrapper =
      oneToOneForeignKeyAssociationsForThisWrapper.Where(
          it =&gt; (it.AssociationEndMembers.All(endMember =&gt; entityTypes.Contains(endMember.GetEntityType()))));
  </code></pre>
  
  <p>is the one that needs some work.  It's using an O(n^2) algorithm when it probably doesn't have to, but I haven't looked closely yet.</p>
  
  <p>EDIT3: Happily, it looks like work in EF6 is fixing this code: <a href="http://entityframework.codeplex.com/discussions/396130" rel="nofollow noreferrer">http://entityframework.codeplex.com/discussions/396130</a></p>