0

Is it possible to generate different databases according to a specific parameter?

My final goal is john.domain.com => create john db, paul.domain.com => create paul db

How could I achieve this using EF6 code first, MVC5? Could model first do it?

1 Answer 1

3

Yes you can change the connection string at runtime, something like. Need to add reference to System.Data.

public static class ConnectionStringExtension
{
    public static void ChangeDatabaseTo(this DbContext db, string newDatabaseName)
    {
        var conStr = db.Database.Connection.ConnectionString;
        var pattern = "Initial Catalog *= *([^;]*) *";
        var newConStr = Regex.Replace(conStr, pattern, m =>
        {
            return m.Groups.Count == 2
                ? string.Format("Initial Catalog={0}", newDatabaseName)
                : m.ToString();
        });

        db.Database.Connection.ConnectionString = newConStr;
    }
}

Usage.

using (var db = new AppContext())
{
    // Uses it just before any other execution.
    db.ChangeDatabaseTo("MyNewDatabase");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.