Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Create Database & Tables At Runtime

I created some tables in an .edmx file and have been generating the database by selecting "Generate Database From Model" and manually executing an .edmx.sql file on the database to build the tables.

Now, however, I am creating a setup dialog that allows the user to connect the program up to their own database. I thought running context.CreateDatabase would be good enough to create the database, along with the tables, but the tables are not created.

What is the preferred method for creating the database and tables when the user specifies their own server and database to use, when originally starting with a model?

like image 831
David Sherret Avatar asked Jul 06 '12 21:07

David Sherret


1 Answers

Ok, I figured out a way of creating the tables and database (not necessarily the best way). The result of CreateDatabaseScript can be executed:

// create the database
db.CreateDatabase();
// grab the script to create the tables
string createScript = db.CreateDatabaseScript();
// execute the script on the database
db.ExecuteStoreCommand(createScript);

You have to do some checking to make sure the tables and database aren't created already, otherwise the application will crash.

I'm going to take a stab at switching my project over to code-first though. Hopefully the above will help anyone looking.

like image 177
David Sherret Avatar answered Sep 28 '22 03:09

David Sherret