Web API & Entity Framework, Where to specify Database connection?
<p>I am going to try and explain this issue as clear as I can.</p>

<p>I start with two projects:</p>

<p><strong>Project One: Data model</strong></p>

<hr>

<p>A repository class that wraps a DbContext that has a single DbSet: RentalListings</p>

<p>This DbContext uses the default settings, so that when I save changes it saves to local DB.</p>

<p><strong>Project Two: Console App</strong></p>

<hr>

<p>Contains a console application that when runs, instantiates an instance of the repository class. </p>

<p>Then it creates multiple "RentalListings" and saves them to the repository.</p>

<hr>

<p>So far so good. After running the console app I check the local DB SQL object explorer, and my repository class has successfuly saved to this db.</p>

<p>Now, I want a way to access this inserted data via a Web API. So I add:</p>

<p><strong>Project Three: Web API</strong></p>

<p>I create a new controller class and add a single GET action method to fetch all listings.</p>

<p>When I run the API project, I can hit the action method, which looks like:</p>

<pre><code>[HttpGet]
public IEnumerable&lt;RentalListing&gt; GetAllListings() {
            StatsRepository repository = new StatsRepository(new StatsContext());
            return repository.GetRentalListings();
        }
</code></pre>

<p>via the correct URL. However I am getting the following error returned:</p>

<pre><code>Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.
</code></pre>

<p>Now, from searching the web I think the issue is that it doesn't know how to access the database??? And that I should specify a connection string in the Web.config file in my Web API project.</p>

<p><strong>Questions:</strong></p>

<p>1) How did my console app, that doesn't specify a connection string, create a mdf database using my repository class?</p>

<p>2) Why doesn't the same work for my web api project? can't it just use the repository to fetch the database, just like the console app did?</p>

<p>Look forward to hearing the replies, thanks in advance!</p>