Automatically Create Database on the Server When app starts

asp.net c# database entity-framework-6 sql-server

Question

I have a WebApi 2 (with EntityFramework 6 - Code-First) / Angular SPA (Built on MVC) application. I would like to just upload my files, open the application on browser and see my database created with the information I set on web.config in connection string.

Since I am going to use the compiled files to create a new web application on the server, I cannot run Update-Database command on the console or use Database Migrations to create a new database.

I just want to compile my application, change the connection string for every different domain and upload to my server. I expect to see a new database with empty tables for every domain this way.


What I Tried So Far

  • I created a database user with SysAdmin and DbCreator roles.
  • I used CreateDatabaseIfNotExists initializer in DbContext

My DataContext Class

public class DataContext : DbContext
{
    public DataContext() : base("DefaultConnection")
    {
        Database.SetInitializer<DbContext>(new CreateDatabaseIfNotExists<DbContext>());
        Database.Initialize(true);
    }
}

Connection String

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Company01;AttachDbFilename=|DataDirectory|\Company01.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />

Right now, my application with this configuration cannot create the database on app start (or on a page where I actually access the database). I have to use Update-Database command from the console in order to create a database.

Using EntityFramework, is it possible to configure an app to automatically check a connection string and if there is no database, create it, on first run?

I would appreciate some suggestions on the subject.

1
1
4/30/2015 5:33:43 PM

Popular Answer

First off, if you specify the database in the connection string and it doesn't exist you cannot connect. Ideally check that the connect fails and then connect without an Initial Catalog= in the connection string. You should then be able to issue the sql commands to create the database, after which close this connection and go back to the one specifyinbg the database.

I don't know whether EF will be able to do that at that point: if you are code-first it should. If you are db first (which I always do) then maybe not, and you'll have to issue all the create etc etc commands directly.

1
4/30/2015 5:27:52 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow