Yanayaya
Yanayaya

Reputation: 2184

Why am I getting an error in my ASP.NET Core SQL Server Express Connection String?

I've recently started a new ASP.NET Core web application and I'd like to connect it to my local SQLExpress database. I've been following the documentation but I'm getting an error of "Value cannot be null" when it tries to read my connection string at

options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")

Here is my code so far. In Startup.cs I have the following setup:

using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Blondie.CoreApiSql.Models;
using Microsoft.Extensions.Configuration;

namespace Blondie.CoreApiSql
{
    public class Startup
    {
        private readonly IConfiguration configuration;
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DatabaseContext>
                (options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }
}

When you run the appliation the error is triggered at the following line:

services.AddDbContext<DatabaseContext> (options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

I have defined the connection string in the appsettings.json as described in the documentation which is as follows:

{
    "ConnectionStrings": {
        "DefaultConnection": "Data Source=DESKTOP-PC009\\SQLEXPRESS;Database=Senua;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
      "IncludeScopes": false,
      "Debug": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "Console": {
        "LogLevel": {
          "Default": "Warning"
        }
      }
    }
  }

I have already created the Senua database with a table in it which has no data. My database uses windows authentication.

I have defined my database context in the following manner with my single table.

public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options) 
        : base(options)
    {
    }
    public DbSet<Hellheim> Hellheim { get; set; }
}

It was my understanding that this error is only typically visibly if you've failed to define your connection string in the appsettings.json file but I've already added it, has anyone had this problem before?

Upvotes: 2

Views: 807

Answers (1)

John Nyingi
John Nyingi

Reputation: 1110

Define and assign a value to Configuration its of IConfiguration and requires a value. Define the Dependency Injection in the constructor

public Startup(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

Upvotes: 2

Related Questions