Entity Framework : Change connection string at runtime

后端 未结 6 1712
半阙折子戏
半阙折子戏 2021-02-04 03:06

Assuming there is an ASP.NET MVC application that uses Entity Framework 6 with code-first approach and StructureMap as IoC.
Also It uses Unit Of Work pattern. Here are the c

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 03:36

    By default the name of the connection string to use in Entity Framework is inferred from the name of you DbContext class. However you can pass the connection string as a constructor parameter:

    public class MyDbContext : DbContext, IUnitOfWork
    {
        public MyDbContext(string connectionString)
            : base(connectionString)
        {
        }
    }
    

    Then you can configure StructureMap to pass in the current connection string e.g.

    For().Use(ctx => new MyDbContext(TheConnectionStringToUse));
    

    This could come from a static value that you set in your code, the current session etc.

提交回复
热议问题