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?
Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file. Child elements include add, clear, and remove.
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With