Change connection string from development to production when publishing

后端 未结 4 1117
野性不改
野性不改 2021-01-13 09:03

I want to know how to change automatically the connection string of my app so when I\'m working on it in my pc, it uses my local SQL Server and once I publish it then uses t

相关标签:
4条回答
  • 2021-01-13 09:40

    I decided to bypass the whole web.config and instead integrate a function that determines the connection string based off of the current machine it is running from. To set this up I had to set up my ApplicationDbContext() to gather the connection string from the function like so:

    public ApplicationDbContext() : base(CFFunctions.GetCFConnection())
    {
    }
    

    Note that my function is Static:

        public static string GetCFConnection()
        {
            string Connection = "";
    
            string Machine = System.Environment.MachineName.ToLower();
    
            switch(Machine)
            {
                case "development":
                    Connection = @"Data Source=DEV_SRV;Initial Catalog=CeaseFire;Integrated Security=True"; 
                    break;
                case "production":
                    Connection = @"Data Source=PRO_SRV;Initial Catalog=CeaseFire;Integrated Security=True";
                    break;
            }
    
            return Connection;
        }
    
    0 讨论(0)
  • 2021-01-13 09:51

    You can now use Azure to handle this exact problem through their connection strings within app settings. You just need to name the connections exactly the same and then it will plug and play.

    https://docs.microsoft.com/en-us/azure/app-service-web/web-sites-configure

    0 讨论(0)
  • 2021-01-13 09:58

    you can split your web.config like

    • web.dev.config
    • web.live.config

    At deployment time choose appropriate config file. You can visit this link to learn how to manage multiple web.config file in single project.

    OR

    If you don't want to create multiple web.config files refer Single web.config file across all environments (dev, test, prod) from codeproject

    0 讨论(0)
  • 2021-01-13 10:03

    The two configs are built for their respective build setting, so you can put your dev connection string in Web.Debug.config and your prod connection string in Web.Release.config. Then, when you deploy to production, run a Release build and your resulting Web.Config will have the production connection string.

    0 讨论(0)
提交回复
热议问题