EF CodeFirstでModelが変化した場合に手動でテーブルを作成する

1480 ワード

/// 
    ///           
    /// 
    /// 
    public class CreateTablesIfNotExist : IDatabaseInitializer where TContext : DbContext
    {
        public void InitializeDatabase(TContext context)
        {
            bool dbExists; //    
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                dbExists = context.Database.Exists();
            }
            if (dbExists)
            {
                bool createTables = false;
                //               
                int numberOfTables = 0;
                foreach (var t1 in context.Database.SqlQuery("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_type = 'BASE TABLE' "))
                    numberOfTables = t1;
                createTables = numberOfTables == 0;
                //           
                if (createTables)
                {
                    //   
                    var dbCreationScript = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
                    context.Database.ExecuteSqlCommand(dbCreationScript);
                    //     
                    context.SaveChanges();
                }
            }
            else
            {
                throw new ApplicationException("No database instance");
            }
        }
    }