Home > Software design >  Why I get Value cannot be null. (Parameter 'connectionString') error message after Adding
Why I get Value cannot be null. (Parameter 'connectionString') error message after Adding

Time:01-06

I have error message while I am trying to Add-Migration and I get error message

Value cannot be null. (Parameter 'connectionString')

What I did so far I check Startup.cs file and I wrote something this

using Microsoft.EntityFrameworkCore;
using ToDoS.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<TodoContext>(opt =>
   opt.UseSqlServer(connectionString));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

So this part I added

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<TodoContext>(opt =>
   opt.UseSqlServer(connectionString));

And here is my connection string

{
  "Logging": {
    "ConnectionStrings": {
      "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ToDoApp;Integrated Security=True"
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

And TodoContext

using Microsoft.EntityFrameworkCore;

namespace ToDoS.Models
{
    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options) : base(options) { }
        public DbSet<Todo> Todos { get; set; }

    }
}

After add-migration InitCreate I get error message. Where I made mistake ? What I am missing here ?

CodePudding user response:

The connection string is defined within the Logging element in your appsettings.json. It should be defined in the root element:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ToDoApp;Integrated Security=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Alternatively, you should be able to get the string by using GetValue:

var connectionString = builder.Configuration.GetValue<string>("Logging:ConnectionStrings:DefaultConnection");
  •  Tags:  
  • Related