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();
}
}
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.
Reasons:
dynamicso the only way is either dynamically load assembly with new classes created prior to creating tables or heavy usage ofReflection.Emitand let your program “write itself”.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.