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."

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,559 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,119 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,815 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ping Ni-MSFT 4,335 Reputation points Microsoft Vendor
    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

    3 people found this answer helpful.

Your answer

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