title: Pass connection string to code-first DbContext
body: <p>How do I pass a connection string to entity framework's code-first DbContext? My database generation works correctly when both DbContext and the connection string in web.config is in the same project and named the same way. But now I need to move the DbContext to another project so I'm testing passing a connection string to it as follows:</p>
  
  <p><strong>Model &amp; Context</strong></p>
  
  <pre><code>public class Dinner
  {
      public int DinnerId { get; set; }
      public string Title { get; set; }
  }
  
  public class NerdDinners : DbContext
  {
      public NerdDinners(string connString)
          : base(connString)
      {
      }
      public DbSet&lt;Dinner&gt; Dinners { get; set; }
  }
  </code></pre>
  
  <p><strong>Action</strong></p>
  
  <pre><code>    public ActionResult Index()
      {
          var db = new NerdDinners(ConfigurationManager.ConnectionStrings["NerdDinnerDb"].ConnectionString);
  
          var dinners = (from d in db.Dinners
                        select d).ToList();
          return View(dinners);
      }
  </code></pre>
  
  <p><strong>Web.Config</strong></p>
  
  <pre><code>&lt;connectionStrings&gt;
    &lt;add name="NerdDinnerDb" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" providerName="System.Data.SqlServerCe.4.0"/&gt;    
  &lt;/connectionStrings&gt;
  </code></pre>
  
  <p>If I set a breakpoint in the action an analyze the <code>db</code>, the connection string is there, but it does not create or find the database or anything.</p>
  
  <blockquote>
    <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)</p>
  </blockquote>