Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ConnectionString property has not been initialized - after first successful query #2576

Closed
milosa opened this issue Nov 28, 2022 · 8 comments
Labels
duplicate This issue or pull request already exists

Comments

@milosa
Copy link

milosa commented Nov 28, 2022

I'm using efcore 7, dotnet 7, NpgsqlEntityFrameworkCore.Postgresql 7.0.0
I have a simple test application, generating an API response with data from postgresql.

When I make the first request to this API, i get the correct data from my database.
But after the first response (i.e. when i refresh the API page in my browser), i get this error (first 3 lines):

System.InvalidOperationException: The ConnectionString property has not been initialized.
   at Npgsql.NpgsqlConnection.Open(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.OpenAsync(CancellationToken cancellationToken)

The first request gives me actual data from the database.

This project uses the API template from Visual Studio for Mac.

This is the AddDbContext part of my Program.cs:

 builder.Services.AddDbContext<PriceListDbContext>(options =>
{
    var dbDataSource = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("PriceListDB"));
    Console.WriteLine(builder.Configuration.GetConnectionString("PriceListDB"));
    dbDataSource.MapEnum<PackagingAmountType>();
    options.UseNpgsql(dbDataSource.Build());
}
);

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "PriceListDB": "Host=localhost;Database=pricelist;Username=postgres;Password=12345;"
  }
}

Controllers/ProductController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PriceList.Data;
using PriceList.Domain;

namespace PriceList.API.Controllers 
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly PriceListDbContext _context;

		public ProductController(PriceListDbContext context)
		{
            _context = context;
		}

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Product>>> GetProductItems()
        {
            return await _context.Products.ToListAsync();
        }
    }
}

PriceListDBContext.cs

using System;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using PriceList.Domain;

namespace PriceList.Data
{
    public class PriceListDbContext : DbContext
    {
        protected override void OnModelCreating(ModelBuilder builder)
            => builder.HasPostgresEnum<PackagingAmountType>();

        public PriceListDbContext(DbContextOptions<PriceListDbContext> options)
        : base(options)
        { 
        }

        public PriceListDbContext()
        : base()
        {
        }

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{ 
        //    var dbDataSource = new NpgsqlDataSourceBuilder("Host=postgresql;Database=pricelist;Username=postgres;Password=12345");
        //    dbDataSource.MapEnum<PackagingAmountType>();
        //    optionsBuilder.UseNpgsql(dbDataSource.Build());

        //}

        public DbSet<Product> Products { get; set; } = null!;
        public DbSet<Price> Prices { get; set; } = null!;
    }
}
@pinkfloydx33
Copy link

pinkfloydx33 commented Dec 3, 2022

I think this is the same as #2555. It seems to manifest in a couple of ways, all which boil down to the same underlying cause. Using the daily build fixes that for me anyways (while waiting for 7.0.1), you might want to try it.

Though, I'm surprised you're not hitting #2557 as well. I wonder what the difference is.

@roji
Copy link
Member

roji commented Dec 3, 2022

Good catch @pinkfloydx33, thanks! @milosa can you please try with the daily build patch version in #2555 and confirm whether that fixes the issue for you?

@pinkfloydx33
Copy link

One thing to note, I think you need to pull the construction of the data source/builder to outside the callback. Otherwise you are going to create a new builder and data source every time you request a context which I believe defeats the purpose.

var dsBuilder = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("PriceListDB"));
dsBuilder.MapEnum<PackagingAmountType>();
var dbDataSource = dsBuilder.Build();

builder.Services.AddDbContext<PriceListDbContext>(options =>
{
    options.UseNpgsql(dbDataSource);
}); 

@roji Please correct me if I'm wrong here. Isn't the guidance one per-Application which the code in OP would be violating, or did I misunderstand a comment you made in gitter?

@roji
Copy link
Member

roji commented Dec 3, 2022

That's correct... OnConfiguring is executed for every DbContext instance, so you should not be building a new data source in there; that effectively disables connection pooling altogether (since each data source corresponds to a pool). I should add a note to our docs around this.

@pinkfloydx33 you may be interested in #2542.

@milosa
Copy link
Author

milosa commented Dec 3, 2022

@pinkfloydx33
Thanks for the code sample, I'll use that from now on.

@roji I just tried, and can confirm the problem is solved in the daily build patch version.

Thanks

@milosa milosa closed this as completed Dec 3, 2022
@roji roji closed this as not planned Won't fix, can't repro, duplicate, stale Dec 3, 2022
@roji
Copy link
Member

roji commented Dec 3, 2022

Duplicate of #2555

@roji roji marked this as a duplicate of #2555 Dec 3, 2022
@roji roji added the duplicate This issue or pull request already exists label Dec 3, 2022
@garisvasm19
Copy link

garisvasm19 commented Jan 10, 2024

Hello world!

I'm developing a .Net api using Docker containers, but at the moment to ask a GET request in swagger, it throws back" The ConnectionString property has not been initialized."which has to do with a database connection failure.

This is the swagger's error:

Captura de pantalla de 2024-01-10 09-06-45

This is the docker-compose.yml file with Postgresql image setup:

services:
 db:
   image: postgres
   restart: always
   environment:
     POSTGRES_USER: postgres
     POSTGRES_DB: my_db
     POSTGRES_PASSWORD: example
   volumes:
     - postgres-data:/var/lib/postgresql/data
 adminer:
   image: adminer
   restart: always
   ports:
     - 8080:8080
 app:
   build:
     context: .
     dockerfile: ./Dockerfile
   ports:
     - 5000:80
   depends_on:
     - db
volumes:
 postgres-data:


This is the ConnectionString in` appSettings.json:


{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "ConnectionStrings": {
      "DefaultConnection": "Host=db;Port=5432;Database=my_db;Username=postgres;Password=example"
    }
  },
  "AllowedHosts": "*"
}


And finally this the dbContext injection in Program.cs:

builder.Services.AddDbContext<EnrollAppTesting>(o => {
     o.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"));
    }
);

I was expecting to make the basic Api operation(GET,POST,PUT,DELETE) into database, but it clearly seems that database is not well configured nor settled.

@jiangyh1024
Copy link

jiangyh1024 commented Sep 14, 2024

#2555

same.. i am running several dotnetcore services in docker and access them from host.. got this "The ConnectionString property has not been initialized." error.

have you solved it ?

by the way, I am connecting to remote database

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

5 participants