
Untitled
By: a guest on
Aug 7th, 2012 | syntax:
None | size: 1.14 KB | hits: 10 | expires: Never
ObjectContext.CreateDatabaseScript not creating indexes
public class CreateTablesIfNotExist<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
public void InitializeDatabase(TContext context)
{
bool databaseExists;
using (new TransactionScope(TransactionScopeOption.Suppress))
{
databaseExists = context.Database.Exists();
}
if (databaseExists)
{
// Check to see if tables are already created
int numberOfTables = 0;
foreach (var t1 in context.Database.SqlQuery<int>("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_type = 'BASE TABLE' "))
numberOfTables = t1;
if (numberOfTables == 0)
{
// Create all database tables
var dbCreationScript = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
context.Database.ExecuteSqlCommand(dbCreationScript);
context.SaveChanges();
}
}
else
{
throw new ApplicationException("No database instance");
}
}
}