Entity Framework : Change connection string at runtime

后端 未结 6 1710
半阙折子戏
半阙折子戏 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:49

    In my experience, I used the Database First mode in EF 6. The DbContext would be generated like below when I add Entity Data Model.

    public TestEntities()
                : base("name=TestEntities")
            {
            }
    

    The TestEntities represent the ConnectionString element in the App.Config

       
    
    
    

    But you can change the default code to below.

    public partial class TestEntities : DbContext
        {
            public TestEntities()
                : base("name=TestEntities")
            {
            }
    
            public TestEntities(string sConnectionString)
                : base(sConnectionString)
            {
            }
    
    ...}
    

    So you got two options to getting DB connection.

    1. using the default. The EF will find the connection string in the config file.

    2. passing the connection string to DbContext.

    The code look like below.

    EntityConnection entityConn =DBConnectionHelper.BuildConnection();
    using (var db = new TestEntities(entityConn.ConnectionString))
    {
    ....
    }
    

    As to the question How to build a EntityConnection?. Please see MSDN EntityConnection.

    Hope it is helpful.

    Thanks.

提交回复
热议问题