سؤال

I have had a dig around for an answer to this issue but everything previously asked seems to be a complex variation on this and doesn't answer the question so I thought I should just ask.

I am developing a three tier application with the following.....

  • DAL - Data Access Layer using Entity Framework
  • BLL - Business Logic Layer
  • Web App - MVC Web Application

I have created an Entity Framework model, repository classes and my connection string is in the DAL App.Config file. I have now created my first class in the BLL and it references the DAL. When trying to test the following, very basic method I get an error relating to a missing connection string in the BLL.

public static List<DAL.Item> getItems() {

        List<DAL.Item> result = new List<Item>();

        DAL.Repositories.ItemRepository myRepository = new    DAL.Repositories.ItemRepository();
        result = myRepository.GetAll().ToList();

        return result;

    }

Why is the BLL looking for the connection string? Am I missing something really obvious here?

If I need to include the connection string across multiple layers, which defeats the purpose of the n-tier structure, then how is the best way to do this? Can anyone shed some light on this for me?

هل كانت مفيدة؟

المحلول

You are new-ing up an instance of the DAL which in turn will try to look at your configuration file (not found due to the scope being in the Business Layer / Unit Test. What you should do is look into Inversion Of Control (IoC) and inject the DAL into the Business Logic Layer. Then you can mock out your DAL that won't try and actually hit the config file / database etc.

نصائح أخرى

Copy the Connection string attribute from app.config to web.config connection string section as is... this iwll resolve

The connection string should be on your presentation layer (mvc project in your case). Just add the entry on the connectionStrings node in web.config and read it by the System.Configuration on the data layer.

define in web.config a connection string

<connectionStrings>
    <add name="ConnectionStringName" connectionString="Data Source=.\SQLEXPRESS; Database=DataBaseName;..." providerName="System.Data.SqlClient" />
</connectionStrings>

in your DataContext of Entity-Framework you can pass the key in the web.config file

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext()
        : base("ConnectionStringName")
    {
    }

    // DbSet properties...
}

To read from configuration file and take a string you have to add a reference for System.Configuration assembly and try this:

using System.Configuration;

string connectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top