How to in-code supply the password to a connection string in an ADO.Net Entity Data Model

前端 未结 4 979
半阙折子戏
半阙折子戏 2020-12-04 13:53

I\'ve been following this tutorial on how to create an OData service.

http://www.hanselman.com/blog/CreatingAnODataAPIForStackOverflowIncludingXMLAndJSONIn30Minutes.

4条回答
  •  长情又很酷
    2020-12-04 14:10

    When you create your context, you can set a connection string. To build this connection string, you can parse the connection string without the password with an EntityConnectionStringBuilder and then parse the inner connection string with an other ConnectionStringBuilder, depending on your browser. Then you can set the password and pass it to the constructor.

    var originalConnectionString = ConfigurationManager.ConnectionStrings["your_connection_string"].ConnectionString;
    var entityBuilder = new EntityConnectionStringBuilder(originalConnectionString);
    var factory = DbProviderFactories.GetFactory(entityBuilder.Provider);
    var providerBuilder = factory.CreateConnectionStringBuilder();
    
    providerBuilder.ConnectionString = entityBuilder.ProviderConnectionString;
    
    providerBuilder.Add("Password", "Password123");
    
    entityBuilder.ProviderConnectionString = providerBuilder.ToString();
    
    using (var context = new YourContext(entityBuilder.ToString()))
    {
        // TODO
    }
    

提交回复
热议问题