Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Update Entity Framework ConnectionString Editor

0.00/5 (No votes)
7 Apr 2014 1  
Helper class

Introduction

When you ship code to others, you are often in the situation where you need to update the connection string. In an Entity Framework system, the connection string is not so easy to change for the untrained user.

In order to help out this situation, I have made a helper class that helps you to update the server and database in the Entity Framework connection string.

All you have to do is use this helper class from your own GUI code (f.x. in an installer)

Using the Code

First you call "LoadConfig". This method loads the config file to be updated.

Then you call "UpdateEntityFrameworkConnection" with the new SQL server name, and the database name. If more EF connection strings exists - all are updated.

Finally you call "SaveConfig", and the config file is written on disk ready to use.

using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Linq;
using System.Xml.XPath;

public class ConnectionStringEditor
{
    private XDocument config;

    public void LoadConfig(string appconfigPath)
    {
        TextReader reader = new StreamReader(appconfigPath);
        config = XDocument.Load(reader);
        reader.Close();
    }

    public void UpdateEntityFrameworkConnection(string server, string database)
    {
        XElement connectionStrings = config.XPathSelectElement("//connectionStrings");

        foreach (XElement connectionString in connectionStrings.Elements())
        {
            if (connectionString.Attribute("connectionString").Value.Contains("metadata"))
            {
                var entityBuilder =
                    new EntityConnectionStringBuilder(connectionString.Attribute("connectionString").Value);
                var cb = new SqlConnectionStringBuilder(entityBuilder.ProviderConnectionString);
                cb.DataSource = server;
                cb.InitialCatalog = database;
                entityBuilder.ProviderConnectionString = cb.ConnectionString;
                connectionString.Attribute("connectionString").Value = entityBuilder.ToString();
            }
        }
    }

    public void SaveConfig(string appconfigPath)
    {
        TextWriter reader = new StreamWriter(appconfigPath, false);
        config.Save(reader);
        reader.Flush();
        reader.Close();
    }
} 

History

  • 7th April, 2014: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here