UncountedBrute
UncountedBrute

Reputation: 506

Startup.cs error on AddDBContext Value must not be null

I am trying to get my connection to a Database to work in .NET Core using Entity Framework. The Models and Context was constructed via DB first approach.

In my startup i have the following lines of code:

// This method gets called by the runtime. 
////Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<PersonalProfileContext>(options => options
      .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddMvc();
}

In my context, i have the following:

public virtual DbSet<Companies> Companies { get; set; }
public virtual DbSet<Qualifications> Qualifications { get; set; }
public virtual DbSet<Roles> Roles { get; set; }
public virtual DbSet<RolesCompanies> RolesCompanies { get; set; }
public virtual DbSet<RolesUsers> RolesUsers { get; set; }
public virtual DbSet<Users> Users { get; set; }

public  PersonalProfileContext(DbContextOptions<PersonalProfileContext> options) 
    : base(options)
{
    return;
}

In the startup.cs i get an error saying Value must not be null on the AddDBContext line.

In my appsettings.json file it is the following:

 {
  "DefaultConnection": {
    "ConnectionString": "" <-- Not included for safety reasons
  },

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "" <-- Not included for security reasons
  }
}

Does anyone know how to resolve this?

Upvotes: 0

Views: 779

Answers (1)

Jamie Taylor
Jamie Taylor

Reputation: 1802

The issue here is that the connection strings section of your appsettings.json is not quite right.

The following is what you have supplied:

"DefaultConnection": {
     "ConnectionString": "" <-- Not included for safety reasons
 }

Whereas what you need it to be is:

"ConnectionStrings": {
     "DefaultConnection": "" <-- Not included for safety reasons
}

This caused the following line to fail:

services.AddDbContext<PersonalProfileContext>(options => options
  .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

As there was no connection string in the ConnectionStrings collection called DefaultConnection, this:

Configuration.GetConnectionString("DefaultConnection")

returns null, which means this:

options
  .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

returns null, meaning that null was being passed into the call to AddDbContext.

It's an easy mistake to make, and not an easy one to spot.

Upvotes: 1

Related Questions