postgresqlasp.net-core

.net core API cant connect PostgreSQL database


I want to create a very simple API using .netCore and PostgreSQL database, here is my app setting

 "ConnectionStrings": {
    "DefaultConnection": "Server=192.xxx.xx.xx;Port=5433;Database=ltw_central_db;User Id=UserNAme;Password = myPass; Timeout = 15;"
}

but I get an error which says Format of the initialization string does not conform to specification starting at index 0 I googled the error and i learned this error indicates something is wrong with my connection string but seems my connection string is fine, any idea?

here is the controller I want tp query and i get error:

   private readonly TenMinutesContext _context;
    public ValuesController(TenMinutesContext context)
    {

        _context = context;
    }
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        var s = _context.stat10mins.Take(5).ToList();

        return null;
    }

My DbContext:

 public TenMinutesContext(DbContextOptions<TenMinutesContext> options) : base(options)
    {
    }
    public DbSet<TenMinutes> stat10mins { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //  modelBuilder.("wpv");
        modelBuilder.Entity<TenMinutes>().ToTable("v_statistics_10_m", "wpv");

        base.OnModelCreating(modelBuilder);
    }

In Appsetting

  public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddDbContext<TenMinutesContext>(opt =>
            opt.UseNpgsql("TenMinutes"));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        var connection = @"Server=192.xxx.xx.xx;Port=5433;Database=ltw_central_db;User Id=UserNAme;Password = myPass; Timeout = 15;";
        services.AddDbContext<TenMinutesContext>
            (options => options.UseNpgsql(connection));

    }

Solution

  • services.AddDbContext<TenMinutesContext>(opt =>
            opt.UseNpgsql("TenMinutes"));
    
        var connection = @"Server=192.xxx.xx.xx;Port=5433;Database=ltw_central_db;User Id=UserNAme;Password = myPass; Timeout = 15;";
        services.AddDbContext<TenMinutesContext>
            (options => options.UseNpgsql(connection));
    

    You have used two AddDbContext and the first one is incorrect.

    I have tried your code using localhost server (Server=localhost) and it will have the same error like what you have gotten.

    It works well when I remove below code.

    services.AddDbContext<TenMinutesContext>(opt => opt.UseNpgsql("TenMinutes"));
    

    For EF core in Postgresql, refer to:

    http://www.npgsql.org/efcore/