简体   繁体   English

实体框架在运行时创建数据库和表

[英]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. 我在.edmx文件中创建了一些表,并通过选择“从模型生成数据库”并在数据库上手动执行.edmx.sql文件来生成数据库来生成数据库。

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. 我认为运行context.CreateDatabase足以创建数据库以及表,但不会创建表。

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: 可以执行CreateDatabaseScript的结果:

// 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. 希望以上内容可以帮助任何人看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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