locked
Where do I put the connection string for my EntityFramework? RRS feed

  • Question

  • Hi;

    I've got EntityFrameworks working fine on my dev system. But now I have 2 questions:

    1. How can I change the server it connects to (we all use Sql Server running on our own desktop - all with the same DB)?

    2. Where do I set it in the config file? I assume it's a connection string, but what is the name for it?

    3. And for cases where I can't put a connection string in the config file (I have to access it from both a MMC and an Exchange transport agent - no {app}.exe.config file access for those), how do I set it?

    thanks - dave


    Who will win The Windward International Collegiate Programming Championships?

    Sunday, October 13, 2013 6:05 PM

Answers

All replies

  • Hi. You can add the connection string as you normally would. Then there is a constructor override for DbContext which accepts the connection string to use as a parameter.

    Connection string in app/web.config:

        <connectionStrings>
          <add name="myConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=myData;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\myData.mdf" providerName="System.Data.SqlClient" />    
      </connectionStrings>

    And when creating your context:

    public class myContext : DbContext
        {
            public HanContext()
                : base("myConnection")
            {
    
            }
    	...
    }


    • Edited by JayChase Monday, October 14, 2013 1:22 AM
    Monday, October 14, 2013 1:22 AM
  • Hi;

    Thank you for the .config example.

    Any idea how to do this when I can't have a .config file?

    thanks - dave


    Who will win The Windward International Collegiate Programming Championships?

    Monday, October 14, 2013 1:34 AM
  • Instead of providing the connection name in the constructor you can pass the whole connection string and that will get used instead (see here for more).
    Monday, October 14, 2013 2:30 AM
  • <copied>

    Any idea how to do this when I can't have a .config file?

    <end>

    http://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnectionstringbuilder.aspx

    • Marked as answer by Fred Bao Monday, October 21, 2013 8:27 AM
    Monday, October 14, 2013 1:12 PM