Wiki

Clone wiki

Boot.Multitenancy / Configcollection

#Create databases with ConfigCollection function

ConfigCollection function return the TenantCollections web.config configuration before it create the FluentConfiguration. Below an example of creating MySql databases in Global.cs (From Application_Start call Init()) This is a safe method of creating databases since there can be no misspelling of database names.

    public static void Init()
    {
        foreach (var tenant in Boot.Multitenancy.Host.ConfigCollection) 
        {
            var configuration = tenant.Value.Configuration;
            var con = new MySqlConnection("Server=127.0.0.1;Port=3306;Uid=boot;Pwd=boot;");
            //try here...
            con.Open();
            new MySqlCommand("CREATE DATABASE IF NOT EXISTS " + configuration.Key + ";", con).ExecuteNonQuery();
            con.Close();
        }
        Host.Init();
    }

Another way is to use an external class.

public class Connect
{
    private string ConnectionString { get; set; }

    /// <summary>
    /// Creates database if it not exist.
    /// </summary>
    /// <param name="dbType">The database type to use. SqlCe, SqlServer2008 or MySql5</param>
    ///<param name="">Database connectionstring</param>
    public Connect(string dbType, string connectionString)
    {
        this.ConnectionString = connectionString;

        switch (dbType)
        {
            case "SqlCe": //Easy because it's local.
                ConnectSqlCe();
                break;

            case "SqlServer2008": //Not implemented
                break;

            case "MySql5": //Not implemented
                break;
        }
    }

    private void ConnectSqlCe()
    {
        try
        { 
            if (!File.Exists(ExtractPath())) {
                var db = new SqlCeEngine(ConnectionString);
                db.CreateDatabase();       
            }
        }
        catch(Exception ex)
        {
            throw new Exception("Ither the path is wrong or the directory is write protected." + "\n " + ex.ToString());
        }
    }

//Extracts the full path to datbasefile.
public string ExtractPath()
    {
        var attachDbFileName = new SqlConnectionStringBuilder(ConnectionString).DataSource;
        return attachDbFileName.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
    }
}

Create each database if not exist. In appstart or your startup class add:

#!c#
foreach (var tenant in Host.ConfigCollection)
            {
                var configuration = tenant.Value.Configuration;
                if(tenant.Value.Configuration.AutoPersist==true)
                 //New Connect class. 
                 new Connect(tenant.Value.Configuration.DbType.ToString(), tenant.Value.Configuration.Connectionstring);
            }
            Host.Init();

Updated