Entity Framework Core Add Migration gives Value cannot be null. (Parameter 'connectionString')

Viewed 6068

I'm new to .NET Core and working through an Udemy class. I'm trying to enable migrations to do code-first but I keep getting an error

Value cannot be null. (Parameter 'connectionString')

I've done some researching and it seems as though most of the time it's misspelling of ConnectionStrings in the appsetttings.json file. However, I've looked all over mine and tried several copy/paste to make sure I have the correct spellings. Either it's something else or I've looked at this so much I'm overlooking something.

Appsettings.json

{
    "ConnectionStings": {
        "DbConnection": "Server=DAVIDPC\\SQLEXPRESS01;Database=dotnet-rpg;Trusted_Connection=true;MultipleActiveResultSets=true;"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*"
}

Startup.cs

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
    services.AddControllers();
    services.AddAutoMapper(typeof(Startup));
    services.AddScoped<ICharacterService, CharacterService>();
}
2 Answers

In your example you misspelled ConnectionStrings

 {
        "ConnectionStrings": {
            "DbConnection": "Server=DAVIDPC\\SQLEXPRESS01;Database=dotnet-rpg;Trusted_Connection=true;MultipleActiveResultSets=true;"
        },
        "Logging": {
            "LogLevel": {
                "Default": "Information",
                "Microsoft": "Warning",
                "Microsoft.Hosting.Lifetime": "Information"
            }
        },
        "AllowedHosts": "*"
    }

Looks good with app settings and configure service method. try this

  "ConnectionStrings": {
    "DbContext": "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=dotnet-rpg;Integrated Security=SSPI; MultipleActiveResultSets=true;",
    "Logging": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  }

the difference is that the connection string doesn't have "Data Source"

In configureService

services.AddDbContextPool<DataContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DbContext"))
            );

Please let me know if this resolved your issue.

Below two reference link has implementation details.

Implement create, read, update, and delete functionalities using Entity Framework Core

Configure Azure SQL relational database using vs 2019

Related