title: how does one programmatically create a localdb .mdf?
body: <p>how does one programmatically create a localdb .mdf?</p>
  
  <p>acceptable solutions <em>exclude</em> visual studio, ssms, aspnet_regsql.</p>
  
  <p>a naive stab at a solution might look like this:</p>
  
  <pre><code>static void Main(string[] args)
  {
      using (var con = new SqlConnection(@"Integrated Security=SSPI;Data Source=(LocalDb)\v11.0;AttachDbFilename=test.mdf"))
      {
          con.Open();
          using (var cmd = new SqlCommand("CREATE DATABASE test", con))
          {
              cmd.CommandType = CommandType.Text;
              cmd.ExecuteNonQuery();
          }
      }
  }
  </code></pre>
  
  <p>but of course, this fails in SqlConnection.Open with the error</p>
  
  <blockquote>
    <p>An attempt to attach an auto-named database for file test.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.</p>
  </blockquote>
  
  <p>You cannot connect to a database if the specified .mdf doesn't exist.</p>
  
  <p>So... how do you create one?</p>