1

我正在尝试创建一个自定义IDatabaseInitializer来仅安装表格。这是我到目前为止所得到的:

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");
        }
    }
}

如果这些表尚不存在,则会正确创建它们,但是它们都没有索引或约束。

ObjectContext.CreateDatabaseScript()生成索引/约束?有谁知道在创建数据库后无需手动重新添加索引的替代方法?

任何帮助深表感谢。

4

0 回答 0