title: Unit Test Entity Framework sets connection string to bin directory instead of App_Data
body: <p>I am trying to run Unit Tests using the Entity Framework.</p>
  
  <p>When I run using debug or release I set my connection string like so:</p>
  
  <pre><code>#if RELEASE
          public DataContext()
              : base("Release")
          {
          }
  #else
          public DataContext()
              : base("Debug")
          {
          }
  #endif
  </code></pre>
  
  <p>My Connection Strings in Web.Config look like:</p>
  
  <pre><code> &lt;connectionStrings&gt;
      &lt;add name="Debug" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\mydatabase.mdf;Initial Catalog=mydatabase;Integrated Security=True" providerName="System.Data.SqlClient" /&gt;
      &lt;add name="Release" connectionString="MultipleActiveResultSets=true;Net=dbmssocn;Server=my.site.com;Database=mydatabase;User ID=myuser;Password=mypass;" providerName="System.Data.SqlClient" /&gt;
    &lt;/connectionStrings&gt;
  </code></pre>
  
  <p>This works great when I simply run my Asp.Net MVC site.</p>
  
  <p>But when I go to run Unit Tests, it looks in the bin directory instead of using the Debug connection string with the debug database in my App_Data directory, even if the project is build against the Debug configuration before running the tests.</p>
  
  <p>The error I get is:</p>
  
  <blockquote>
    <p><em>System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Cannot attach
    the file
    'D:\Development\Projects\myproject\MyProject\bin\mydatabase.mdf</em></p>
  </blockquote>
  
  <p>Why is it looking in the bin directory instead of using the App_Data path defined in the connection string?</p>
  
  <p><strong>ANSWER:</strong></p>
  
  <p>The answer was to set the data directory in the App Domain like this in the Test Fixture Setup in my Base Test Class:</p>
  
  <pre><code>public class TestBase
  {
      [TestFixtureSetUp]
      public void Setup()
      {
          var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
          var appDataDirectory = Path.Combine(baseDirectory.Replace("\\bin", ""), "App_Data");
  
          AppDomain.CurrentDomain.SetData("DataDirectory", appDataDirectory);
      }
  }
  </code></pre>