Click here to Skip to main content
15,880,503 members
Articles / Entity Framework
Tip/Trick

Update Entity Framework ConnectionString Editor

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
6 Apr 2014CPOL 9.9K   8  
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer UCL Erhvervsakademi og Professionshøjskole UCL Erhvervsakademi og Professionshøjskole
Denmark Denmark
ORCID: 0000-0002-8974-2718

Comments and Discussions

 
-- There are no messages in this forum --