Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5 / MVC 6 Database First - No connection string named MyEntity could be found in the application config file

Our ASP.NET 5 / MVC 6 project accesses our DB by going through a Business layer assembly then down into DAL (Database First) assembly. The MVC 6 code blows up when trying to execute the Business layer code which uses the DbContext to access the DB with error: No connection string named 'MyEntity' could be found in the application config file. I have tried defining the MyEntity connection string in the MVC project config.json, appsettings.json in various ways with no luck.

If executing Business layer methods from a tester project where I have the expected app.config file with connection string syntax as below it works no problem.

Note This question could also be restated as how to migrate a MVC 5 to MVC 6 app, where the MVC 5 app loosely coupled DB access to DAL layer and the MVC code had NO knowledge of EF and ONLY supplied the web.config connection string needed by DbContext object in DAL?

Any help would be appreciated, let me know if you need any more information.

Config file syntax in Tester project:

<add name="MyEntity" 

connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyServer;initial catalog=MyDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
providerName="System.Data.EntityClient" />

Likely wrong syntax in config.json file.

{
  "Data": {

"defaultConnection": {

"connectionString": "metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyServer;initial catalog=MyDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
    },

"entityFramework": {

"MyEntity": {

"ConnectionString": "name=data:defaultConnection:connectionString"
      }
    }
  }
}
like image 373
Dave Avatar asked Oct 30 '22 09:10

Dave


1 Answers

How is the database context created?

Migrate Configuration Settings from web.config

The connection string can be in appsettings.json

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
        }
    }
}

Edit You can get your connection string as follows:

string connection = Configuration.Get<string>("Data:DefaultConnection:ConnectionString");
like image 83
Rami A. Avatar answered Nov 11 '22 15:11

Rami A.