简体   繁体   中英

Remove ConnectionString from Web.config using Entity Framework CodeFirst

Transform web.config won't work well for Entity Framework CodeFirst because the connection string is added dynamically after transform when publishing. We have a dynamic connection settings being set in code for CodeFirst when releasing to different environments.

I have tried the correct removal method but the published results ends up with the connection string in the web.config .

Are there any work arounds for this? Putting connection info in our web.config s isn't an option. Adding the connection info dynamically at runtime works well.

The problem is when publish adds the connection info in the web.config the app gets a 500 error because codefirst is attempting to use an invalid connection string for the environment that is not sandbox where it was created.

We are changing that at runtime here and that is working.

public MyAppDataContext()
{
   this.Database.Connection.ConnectionString = OurDynamicConfigSettings.GetSetting("MyAppConnectionString");
}

The codefirst though is attempting to use what is in web.config before we set it dynamically. The fix is to remove the connection info from the web.config.

It all works except when building on build server or publishing, codefirst inserts the connection info back into the web.config every time we publish. Having to remember to remove this each time is not good practice and prone to errors if you forget.

Code for removing connection string in our transform file should work but doesn't.

<connectionStrings>
    <add xdt:Transform="Remove" xdt:Locator="XPath(configuration/connectionStrings[@name='MyAppConnectionString'])" />
</connectionStrings>

Your transform should be:

<connectionStrings>
    <add xdt:Transform="Remove" xdt:Locator="Match(name)" name="MyAppConnectionString" />
</connectionStrings>

But, I have to ask.. are connection strings stored in your database or something? Why do you need to do them in code?

You could just do this:

public class MyDataContext : DbContext {
     public MyDataContext(string connectionString) : base(connectionString)

   ...
}

Then when you create you contexts, you do this:

using(var context = 
   new MyDataContext(OurDynamicConfigSettings.GetSetting("MyAppConnectionString"))) {
    ...
}
 public partial class MyContextEntities : DbContext
    {
        public MyContextEntities(string ConnectionString="[Your Entity Connection String Here]")
            : base(ConnectionString)
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
}

Replace " with ' (single quote) in connection string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM