title: How do I create a SQL Server Express database at runtime in a C# MVC App?
body: <p>I'm trying to do this using Entity Framework 5 in C# in an MVC3 web application:</p>
  
  <pre><code>// Local DB connection
  var dbId = String.Format(@"Data Source=.\SQLEXPRESS;AttachDbFilename={0}.mdf;Database=Tests;Integrated Security=True;Pooling=False;Connect Timeout=30;User Instance=True", _dbPath);
  _connection = new SqlConnection(dbId);
  
  Database.SetInitializer&lt;MyContext&gt;(new DropCreateDatabaseAlways&lt;MyContext&gt;());
  
  // Reset database if the file exists
  var ctx = new MyContext(_connection);
  ctx.Database.CreateIfNotExists();
  ctx.Database.Initialize(true);
  ctx.SaveChanges();
  
  return _connection;
  </code></pre>
  
  <p>This works for my tests, but not when I run the web application. When I run the web application, I get:</p>
  
  <blockquote>
    <p><em>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: SQL
    Network Interfaces, error: 26 - Error Locating Server/Instance
    Specified)</em></p>
  </blockquote>
  
  <p>I see in a few other questions people have suggested removing the 'User Instance' from the connection string, but that results in:</p>
  
  <blockquote>
    <p><em>CREATE DATABASE permission denied in database 'master'.</em></p>
  </blockquote>
  
  <p>Let me be entirely clear on my goal here: I'm trying to have the web application create database instances (<code>sqlexpress</code>) on demand. </p>
  
  <p>Creating the database instances <em>in advance</em> is not a solution.</p>
  
  <p>I'm quite puzzled about why some kind of special permission is needed when the app worker is the one accessing <em>and creating</em> the database.</p>
  
  <p>How can you do this?</p>
  
  <p>Using sqlite this is a trivial operation, and I'm starting to feel like using Entity Framework (and thus SQL Server Express) was mistake and I should have gone with fluent nhibernate and sqlite instead. </p>