How to include ampersand in connection string?

I’m using Entity Framework 4 for a simple app and would like to bake my connection credentials into the following connection string:

    <add name="MyEntities"    
         connectionString="metadata=res://*/MyDataModel.csdl|res://*/MyDataModel.ssdl|res://*/MyDataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=localhostDEV;Initial Catalog=MyDB;UserId=myUser;Password=jack&jill;MultipleActiveResultSets=True&quot;" 
         providerName="System.Data.EntityClient" />

However, the password (which I cannot change) contains an ampersand. ASP.NET throws:
Configuration Error: An error occurred while parsing EntityName. Line XX, position YYY.

If I replace the ampersand in the password with &amp;, I get a SqlException: Login failed for user 'myUser'. Usually this trick works, but I’m guessing that something is failing because this is technically a connection string inside a connection string.

What should I do here? Most of my classes include code like:

using (var context = new MyEntities()) {
   // do work

Update: It turns out that the credentials I am using are a domain account, so what I really need is Integrated Security=True in the connection string rather than a password.

Encoding the ampersand as indicated in the accepted answer should work fine, though I haven’t tested it.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’ll need to use escape sequences like you would for any XML document, which is all the .config files are.

  • Ampersand = & = &amp;
  • Greater Than = > = &gt;
  • Less Than = < = &lt;
  • Apostrophe = ‘ = &apos;
  • Quote = ” = &quot;

You can also use the CDATA tag so that you can use these illegal characters

<![CDATA[ and ends with ]]>

    <add name="MyEntities" connectionString="
        provider connection string=&quot;
        Data Source=localhostDEV;
        Initial Catalog=MyDB;UserId=myUser;
        providerName="System.Data.EntityClient" />

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x