EF Code First to create multiple databases dynamically

喜你入骨 提交于 2020-01-16 18:06:08

问题


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:


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


来源:https://stackoverflow.com/questions/25300828/ef-code-first-to-create-multiple-databases-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!