horgh
horgh

Reputation: 18534

EntityFramework can't see ConnectionString in the App.config

I am studying Code First EntityFramework together with ASP.Net MVC 3. At first my trivial EFDbContext class was placed in the WebUI mvc project in a Concrete folder.

 public class EFDbContext : DbContext
 {
     public DbSet<Product> Products { get; set; }
 }

And it was consumed through

 public class EFProductRepository : IProductRepository
 {
    private EFDbContext context = new EFDbContext();

    public IQueryable<Product> Products
    {
        get
        {
            return context.Products;
        }
    }
 }

where

public interface IProductRepository
{
    IQueryable<Product> Products { get; }
}

So I added the following code to the root Web.config:

 <connectionStrings>
      <add name="WebUI.Concrete.EFDbContext" connectionString="Data Source=HORGH\SQLSERVER2008;Initial Catalog=SportStore;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient"/>
 </connectionStrings>

and it worked.

Then I decided to take it into a separate Domain Class Library project. There I have an App.config file. So I decided to move my connection string there, and it became to be:

<connectionStrings>
      <add name="Domain.Concrete.EFDbContext" connectionString="Data Source=HORGH\SQLSERVER2008;Initial Catalog=SportStore;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient"/>
 </connectionStrings>

But eventually EF stopped seeing it.

EFProductRepository and EFDbContext moved to the Domain project with their root folder Concrete. So the code calling the constructor is in EFProductRepository, i.e. in Domain project.

I tried to rename App.config to Web.Config; tried to return the connection string back to the Web.config of the WebUI project. It doesn't work neither.

What am I doing wrong?

Upvotes: 9

Views: 13098

Answers (2)

Ivan Turovets
Ivan Turovets

Reputation: 164

Use connection string name without namespace

<connectionStrings>
    <add name="EFDbContext" connectionString="Data Source=HORGH\SQLSERVER2008;Initial Catalog=SportStore;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Upvotes: -1

Eric J.
Eric J.

Reputation: 150108

Class Library project and App.config file don't mix.

The application's configuration file is always associated with an executable, or in the case of web.config, with a website.

Your DLL project cannot (and should not) have its own config file*.

Instead, configure the connection string along with your WebUI project. You can have multiple connection string entries.

*There are actually ways to cause your DLL to in fact have its own config file. NLog, for one, does that. However, it is seldom a good idea.

Upvotes: 20

Related Questions