简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM