如何创建表的SQL数据库实体框架,运行时和更新模型在运行时?实体、框架、模型、数据库

2023-09-08 09:48:07 作者:我的生活依旧

我知道,当我使用ado.net,我可以创建数据库或表在运行时编程方式,如:

I know that when I use ado.net, I can create database or table at run-time programmatically like:

String str;
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");

str = "CREATE DATABASE MyDatabase ON PRIMARY " +
    "(NAME = MyDatabase_Data, " +
    "FILENAME = 'C:\\MyDatabaseData.mdf', " +
    "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
    "LOG ON (NAME = MyDatabase_Log, " +
    "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
    "SIZE = 1MB, " +
    "MAXSIZE = 5MB, " +
    "FILEGROWTH = 10%)";

SqlCommand myCommand = new SqlCommand(str, myConn);
try 
{
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
}

但我使用实体框架和我有一些工作中,我要在运行时创建表。我搜索了很多关于它,但是没有办法,我得到了。任何帮助将是AP preciated。

But I am using entity framework and I have some work in which I have to create tables at runtime. I have searched a lot about it but no way I got. Any help would be appreciated.

推荐答案

实体框架是不适合的场景,你没有静态的数据库架构。

Entity framework is not for scenarios where you don't have static database schema.

原因:

在实体框架的映射是静态的 - 动态修改要求,对描述映射在运行时,用修改过的文件,而不是XML文件修改 即使改变映射您还没有更改或新建的实体类在code。 EF不支持动态所以要么是动态加载程序集创建表或 Reflection.Emit的键,让你的程序自己写出来。 Entity framework mapping is static - dynamic modification requires, changes of XML files describing the mapping at runtime and using modified files instead. Even with changed mapping you still don't have changed or newly created entity classes in your code. EF doesn't support dynamic so the only way is either dynamically load assembly with new classes created prior to creating tables or heavy usage of Reflection.Emit and let your program "write itself".

如果你只需要创建一个数据库,但表将永远同你应该罚款。您可以使用ADO.NET code创建数据库和表,只修改的连接字符串传递给上下文的构造函数。但要求是静态的数据库模式=表的定义没有改变。

If you only need to create a database but tables will be always same you should be fine. You can use that ADO.NET code to create database and tables and pass only modified connection string to the constructor of your context. But the requirement is static database schema = no changes in table's definition.

 
精彩推荐
图片推荐