0

My WinForm app realizes MVC pattern and consists of two projects. The first one contains View and Controller layers and the second one- Model layer(class library).

The application has to get information from database (I use MS SQL Server).

In the second project (Model layer) i have ADO.NET model, methods to work with the database and appropriate connection string in app.config. But when i run the app and it tries to make a query to the database the error "Could not find the connection string with the name ... in the application configuration file" appears.

I guess that when Controller call a Model's method to make a query to the database app tries to find connection string in App.config file of the main project and can't find it there. I think it's not right to create a connection string in the project with Controller and View.

How can i solve the problem in the right way?

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
Andrei
  • 749
  • 6
  • 7

1 Answers1

1

The App.config (or Web.config where appropriate) belongs to the application, not to any class libraries.

If your Controller/View layers are a Windows Forms project and your Model layer is a Class Library project then the App.config belongs in the Windows Forms project.

I think it's not right to create a connection string in the project with Controller and View.

It has nothing to do with the Controllers and Views. The App.config isn't part of the MVC pattern. It has everything to do with the configuration of an application for an environment. Any given class library should be portable across applications and environments. Any given application should be configured to execute in the environment to which it's deployed.


Basically, put your App.config values in the application's App.config.

David
  • 208,112
  • 36
  • 198
  • 279
  • I add connection string in settings of Winforms project, run the application but get error: "System.Data.Entity.Infrastructure.UnintentionalCodeFirstException" – Andrei Apr 15 '16 at 16:32
  • @Andrei: Did you look up that exception on Google? It seems that there's a conflict between how you're using Entity Framework and the connection string you're providing. This might help: http://stackoverflow.com/questions/5940616/model-first-with-dbcontext-fails-to-initialize-new-database – David Apr 15 '16 at 16:35
  • The error appears in OnModelCreating method of DbContext class. This method is called by itself in the moment when a LINQ query to database is initialized. – Andrei Apr 15 '16 at 16:49
  • Thanks, I'll read it. btw, in comments to the error there is a phrase that "Context is used in Code First model with code created from EDMX-file for developing DataBase First or Model first. Proper work of such a combination is imposible" – Andrei Apr 15 '16 at 17:08