1
votes

I have a ASP NET CORE project, where I have a connection string and my dbcontext is in a .net 4.52 class library project. I would like to know how to access the connection string from the asp net core project.

asp net core - appsettings.json:

"ConnectionStrings": {        
    "MyConnectionString": "Data Source=.\\mydb;Initial Catalog=mydb;User Id=myuser;Password=mypassword; MultipleActiveResultSets=true"
}, ...

My dbContext:

public MyContext() : base("name=MyConnectionString")
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>());
}

public MyContext(string connString) : base(connString)
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>());
}

When I run the app I get the error: no connection string named MyConnectionString could be found in the application config file. Even if I add a connection string section to the asp net core project web.config file.

When I hardcode the connectionstring everything works fine.

1

1 Answers

0
votes

I had the same problem and it led to a lot of headaches for me. Here's how I solved it:

Visual Studios Problems

First of all I had created a .NET Core website using Visual Studios 2015 and a pre-release version of .Net Core (dnx something or another). I kept going over my appsettings.json file and trying to figure out how to fix it but to no avail. All the research I was did said that I was on an old version of the .Net core framework and I need to upgrade. Finally I got sick of it and uninstalled VS15 and installed VS17 so I'd get the latest greatest.

Wrong Project Type

Now armed with VS17, I created a brand new .Net Core web application and added my IO class only to get the error

"The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0."

I got that error because I was trying to use a .Net framework OI class in a .Net Core website. Rather than go down that road I decided to create a .Net framework ASP.Net Core website. (Yeah, a little confusing)

enter image description here

This problem with the mscorlib might be getting fixed soon?

Same Old Problem

After I got that squared away, re-added my IO class, and then added my connection string to the appsettings.json only I had the exact same problem.

InvalidOperationException: No connection string named 'myConnectionString' could be found in the application config file.

Before I threw my PC out the window, I noticed that this time there was an app.config file along with the appsettings.json file.

enter image description here

Solution

On a hunch I took my connection string out of the appsettings.json and added it to the app.config and Voila! It worked! I'm not sure if this will work for the old DNX framework in VS15 but I'd try adding the app.config if you're still having this issue.