65.9K
CodeProject is changing. Read more.
Home

Update Entity Framework ConnectionString Editor

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Apr 7, 2014

CPOL
viewsIcon

10271

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