0

Well, I have two projects:

  • Blog.Core (a class library project for my entites as well as data access code)
  • Blog (ASP.NET MVC Project)

I installed EF in Blog.Core. Then added reference to Blog.Core in Blog. I have specified my connection string in Blog.Core since this is my DAL. Now when I run the project I get the following error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

I deleted the connection string form Blog.Core and placed it in Blog project, and it works. Why is that? Doesn't this break the architecture because client-side has the database connection string? I mean isn't that correct that only DAL should be responsible for connection strings and database operations. Why was my first (and, according to me, more logical) solution not working?

Aneeq
  • 416
  • 3
  • 15
  • the connection string has to be where the CONTEXT is initialized. Since the context is usually short-term, you can take care that only the DAL initializes a context, or make sure the instantiation is done on DAL layer. Since DAL should implement simple functions for accessing database items, you can encapsulate it in this way, if you actually need to do this. – DevilSuichiro Jul 23 '16 at 15:05
  • @DevilSuichiro My **Context** is in main DAL but why does my connection string has to be in Blog (ASP.NET MVC) project instead of DAL (class library)? I mean is there any specific reason for this behavior? – Aneeq Jul 23 '16 at 16:27
  • not where the context is declared is relevant, but where it is instantiated, that is the first DB call within it after model building. this is because the context looks for the connection string in the app.config in the current active project, since anything else would be counter-intuitive; using the same context from different places in the code to target multiple databases would be much harder, too. – DevilSuichiro Jul 23 '16 at 17:04

1 Answers1

0

There has been lots of argument about this one and you can refer to this thread C# DLL config file

Community
  • 1
  • 1
super-user
  • 1,017
  • 4
  • 17
  • 41