How to Fix "The ConnectionString property has not been initialized." In ASP.NET Core 8,MVC in visual studio 22

Merlyn Coleman 0 Reputation points
2024-02-18T17:24:48.8866667+00:00

I am working on a project called:"MecoManageMovies" Using ASP.NET Core 8, C# MVC in Visual Studio 22 In Update_Datebase in PM, I get:"The ConnectionString property has not been initialized."

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
SQL Server | Other
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2024-02-19T02:07:23.4633333+00:00

    Hi @Merlyn Coleman,
    The error message is caused by the connection string is not in appsettings.json/ appsettings.Development.json(it cannot find the connection string If your environment is not Development when you store it in appsettings.Development.json) . Be sure your connection string stores in appsettings.json. And the root key name must be ConnectionStrings, for example:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
    
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    }
    

    Also be sure the key name is spelled correctly, you can set the breakpoint to check if the connectionString variable contains value:

    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    builder.Services.AddDbContext<YourDbContext>(options =>
        options.UseSqlServer(connectionString));
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Rena

    4 people found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.