System.InvalidOperationException: The ConnectionString property has not been initialized. ASP.NET Core 7

tjestesjr77 20 Reputation points
2023-03-08T17:07:45.6433333+00:00

I am encountering the following error when I debug my application.

System.InvalidOperationException: The ConnectionString property has not been initialized.

Otherwise, if I don't debug it just shows no data. I am very new to ASP.net and not sure how to continue to debug this, any help appreciated.

Program.cs

sing QsccDevAlpha.Models;
using Microsoft.EntityFrameworkCore;
using QsccDevAlpha.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<QsccDevAlphaDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDbContext<QSCC_QAContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("QA_Context")));
builder.Services.AddControllersWithViews();
builder.Services.AddMvc().AddJsonOptions(options => {
    options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
builder.Services.AddScoped<IStateProvRepository, StateProvRepository>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else
{
    app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

QA_Context

using Microsoft.EntityFrameworkCore;
using QsccDevAlpha.Models;
namespace QsccDevAlpha.Data;
public partial class QSCC_QAContext : DbContext
{
    public QSCC_QAContext()
    {
    }
    public QSCC_QAContext(DbContextOptions<QSCC_QAContext> options)
        : base(options)
    {
    }
    public virtual DbSet<AssetsByAssociate> AssetsByAssociate { get; set; }

Controller

using Microsoft.AspNetCore.Mvc;
using QsccDevAlpha.Data;


namespace QsccDevAlpha.Controllers
{
    public class AssetsByAssociatesController : Controller
    {
        private readonly QSCC_QAContext _context;

        public AssetsByAssociatesController(QSCC_QAContext context)
        {

            _context = context;
        }

        public IActionResult List()
        {
            return View();
        }
        [HttpGet]
        public JsonResult GetAssetsByAssociateData()
        {
            var data = _context.AssetsByAssociate.ToList();
            return Json(data);
        }
    }
}

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=QSCCWSQL01.QSCC.local;Database=QsccDevAlpha;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;Encrypt=True"
    //How do we want to handle security.  Which account to connect with?  Encrpted connections? Etc...
    //;TrustServerCertificate=True
    //;Encrypt=False

  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStringQA": {
    "QA_Context": "Data Source=QSCCWSQL01.qscc.local;Initial Catalog=QSCC_QA;Integrated Security=True;TrustServerCertificate=True;MultipleActiveResultSets=true;Encrypt=True"
  }
}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,242 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,317 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,046 Reputation points Microsoft Vendor
    2023-03-09T06:14:16.2066667+00:00

    Hi @tjestesjr77

    System.InvalidOperationException: The ConnectionString property has not been initialized.

    builder.Configuration.GetConnectionString("QA_Context")

    This issue relates the above code.

    When use the GetConnectionString() method, it will look for a configuration value whose key is ConnectionStrings:<connection string name>. But in your appsettings.json file, the QA_Context doesn't locate inside the ConnectionStrings key, so the connection string will be null, and will show the ConnectionString property has not been initialized error.

    To solve this issue, you can get the QA_Context value use: builder.Configuration["ConnectionStringQA:QA_Context"]

    builder.Services.AddDbContext<QSCC_QAContext>(options =>
        options.UseSqlServer(builder.Configuration["ConnectionStringQA:QA_Context"]));
    

    Or you can change the appsettings.json file as below:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=QSCCWSQL01.QSCC.local;Database=QsccDevAlpha;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;Encrypt=True",
        "QA_Context": "Data Source=QSCCWSQL01.qscc.local;Initial Catalog=QSCC_QA;Integrated Security=True;TrustServerCertificate=True;MultipleActiveResultSets=true;Encrypt=True"
    
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*", 
    }
    

    Then you can use the GetConnectionString() method to get the connection string, in this scenario, use the following code:

    builder.Services.AddDbContext<QSCC_QAContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("QA_Context")));
    

    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,

    Dillion

    4 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Michael Taylor 49,251 Reputation points
    2023-03-08T21:10:03.2033333+00:00

    In your call to AddDbContext you're creating 2 different DB contexts. Do you really need to connect to 2 different databases at the same time? Note that you should have 1 DbContext for each database you're connecting to and not a DbContext for each environment. If your app is only talking to 1 database in each of your environments then you only need 1 DbContext registered.

    When you register the context you give it the name of the connection string in your settings file. Based upon your settings file you have a single connection string called DefaultConnection. But in your registration code you're referring to a QA_Context connection string but that doesn't exist in your settings file and hence the connection will fail. Either add the connection string to your settings file or modify your registration code to just use the DefaultConnection string that you already have declared.

    Note that you have an appsettings file for each environment normally. So your appsettings.json file is your base file and that is where you generally put your development settings like your dev DB connection string. You then create additional appsettings.<env>.json files for each environment (e.g. appsettings.qa.json for your QA environment). Within the environment-specific file you override any settings that are different in your root appsettings.json file. Normally this would include any connection strings (to point to your QA database) and links to services and APIs that are in your QA environment. You should not have separate connection strings in the same settings files for different environments.

    When you publish your app (or deploy it) then ensure that your root appsettings.json file get copies to the directory where your site goes. Also ensure that your appsettings.<env>.json file gets copied as well. The runtime will then handle the rest. This is the default behavior for the runtime but you must have an environment variable defined on the machine (or in Azure settings if you deploy there) that sets the environment name correctly. Refer to the discussion here.

    Finally note that you should remove the default constructor for your DbContext class. Otherwise the options won't get properly sent to your constructor.

    0 comments No comments