Reputation: 1720
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.
Upvotes: 2
Views: 6458
Reputation: 41
Please read this thread: NHibernate / Fluent NHibernate Dynamic Column Mapping
better off using a key-value store such as Redis or a schema-less database like CouchDB instead of SQL
Upvotes: 1
Reputation: 364279
Entity framework is not for scenarios where you don't have static database schema.
Reasons:
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".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.
Upvotes: 6
Reputation: 1634
Entity Framework also has similar functions like myCommand.ExecuteNonQuery();
, you may try SomeEntities.ExecuteStoreCommand("some sql statements")
.
Considering Entity Framework requires mappings between data models and database, it looks not possible to create/modify tables directly with integrated query language (otherwise the data models need to be modified at run time). Therefore, with no solid references supporting this point of view, I think SomeEntities.ExecuteStoreCommand()
may be the only way.
Upvotes: 2