Search code examples
c#.net-coreentity-framework-core

How to set connectionstring from appsettings.json in Entity Framework Core


I'm setting up a new database with Entityframework Core and code first approach. I have set up a context class like in the code listing below and all needed classes for the database tables too. Now I want to create the new database with

using (var context = new MyContext())
{
    context.Database.EnsureCreated();
}

But what I get is an error, that the connectionstring cannot be null.

My Connectionstring is set in the appsettings.json file an I copy this to the output directory when the project builds.

I have tried different ways to get the connectionstring from the appsettings file but all with the same result. In the Configuration Property in the Startup class I can see that the appsettings file is loaded correctly but when I want to get the string with

ConnectionString = Configuration["Connectionstrings:MyConnection"];

the ConnectionString is allways null.

I have this in my Startup.cs File:

 public class Startup
 {
    public static string ConnectionString { get; private set; }
    public IConfigurationRoot Configuration { get; set; }

    public Startup(IHostingEnvironment _environment)
    {
        Configuration = new ConfigurationBuilder()
                        .SetBasePath(_environment.ContentRootPath)
                        .AddJsonFile("appsettings.json")
                        .Build();
    }

with the following in the Configure - Method

using (var context = new MyContext())
{
    context.Database.EnsureCreated();
}

And in my context class I have the following code

public class MyContext : DbContext
{
    public MyContext()
    {
    }

    public static string GetConnectionString()
    {
        return Startup.ConnectionString;
    }

protected override void OnConfiguring(DbContextOptionsBuilder _builder)
{
    _builder.UseSqlServer(GetConnectionString());
}

So now, when I start the application I get the error in the OnConfiguring - Method that the connectionstring cannot be null.

And my appsettings.json file is

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "Connnectionstrings": {
    "MyConnection": "server=.;database=MyDatabase;trusted_connection=true;MultipleActiveResultSets=True"
  },
}

Solution

  • The ConnectionString is allways null because there is a typo, try this

    ConnectionString = Configuration["Connnectionstrings:MyConnection"];
    

    or fix name in appsettings.json