WinForms Entity Framework database connection exception at design-time

c# design-time entity-framework-6 visual-studio-2017 winforms


Environment: I have a Visual Studio 2017 solution with a Model project containing Entity Framework (EF6) DbContext and POCOs, a data access layer project implementing the Repository and Unit Of Work patterns, and a WinForms UI project. In the UI main form there is a tab control and on one of the tab-pages there is a UserControl. On the UserControl there is DataGridView. In the UserControl's Load method, I get some data from the database via the UnitofWork (which gets data from EF) and use that data to populate the DataGridView (not using Data Binding).

Problem: At design-time, when I open the main form designer, I get a SQL Server connection Exception "A network-related or instance specific error occurred while establishing a connection to SQL Server. The server was not found or is not accessible....". The stack trace shows that it is running the code that populates the DataGridView, but cannot connect to the database at design-time. Everything works fine when I build and run the application.

Already researched/found: This SO answer shows that I can use if (!DesignMode) {...} to wrap around code that I don't want to run at design time. That's okay but I'm going to be adding many more of these UserControls and I'm looking for a cleaner solution. Is there a simple (as in a few lines of code) way to...

  1. Tell EF to return empty lists of objects at design time?


  1. Give EF a connection sting to use at design-time so it can successfully hit the database?

I have not added any connection string to App.config. I'm simply working with Entity Framework's default connection to localDb.

6/11/2017 8:41:11 AM

Popular Answer

After re-installing Windows, SQL Server and Visual Studio, I got the same behaviour. After more searching it has become obvious that Visual Studio will always run a UserControl's Load method at design-time when you add the UserControl to a form or open the designer of a form that contains the UserControl. The solution is to test the value of the DesignMode property in the Load method.

private void MyUserControl_Load(object sender, EventArgs e)
    if (!this.DesignMode)
        // do stuff here, if it involves connecting to the database
6/15/2017 9:30:43 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow