0

I'm failing to connect to PostgreSQL using Npgsql in my local environment I have checked each and every thing looks fine and I'm able to connect using my pgAmin and also I have managed to update tables after creating migrations I don't know where I'm doing it wrong where I try to open the connection so as I can insert data into the table I have created below is my implementation.

appsettings.json

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

Controller method to insert data

 private readonly string _connectionString;

  public DataLoader(string connectionString)
  {
  _connectionString = connectionString;
  }

    public async Task LoadToDatabase(IEnumerable<Customer> data)
     {
    
         try
         {
             await using var connection = new NpgsqlConnection(_connectionString);
             await connection.OpenAsync();
    
             foreach (var customerDetails in data)
             {
             await connection.ExecuteAsync("INSERT INTO Customer (CustomerCode, CustomerNames,OrderId, Location) VALUES (@CustomerCode, @CustomerNames, @OrderId, @Location)", customerDetails);
             }
    
             await connection.CloseAsync();
         }
         catch (NpgsqlException ex)
         {
             // Log error (log to a file, console, etc.)
             Console.WriteLine($"Error opening PostgreSQL connection: {ex.Message}");
         }
         catch (Exception ex)
         {
             // Log error (log to a file, console, etc.)
             Console.WriteLine($"An error occurred: {ex.Message}");
         }
     }

Program .CS class

// Add services to the container.
builder.Services.AddControllers();

// Adding configuration
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

// Getting the configuration
var configuration = builder.Configuration;

// Retrieving connection string from configuration
var postgreconnection = configuration.GetSection("ConnectionStrings:DefaultConnection").Value;

// Configuring PostgreSQL Database connection
builder.Services.AddDbContext<ApplicationDbContext>(options =>options.UseNpgsql(postgreconnection));

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSingleton(new DataExtractor());
builder.Services.AddSingleton(new DataTransformer());
builder.Services.AddSingleton(new DataLoader(postgreconnection));

No firewall is blocking, any suggestions will be much appreciated.

7
  • You setup a DbContext but don't use it? You have debugged your code have seen that the connectionstring is correctly read from the configuration and you can tell us the actual error/exception you get? Commented Jun 10, 2024 at 11:06
  • Sidenote. LoadToDatabase sound totally weird when you INSERT something into the database. Its saving not loading. Commented Jun 10, 2024 at 11:09
  • And the exact error is...? Kinda weird to mess about with EF Core, if all you are doing is executing raw queries. Why not just use Dapper? Commented Jun 10, 2024 at 11:10
  • Thanks for your responses however LoadTodatabase is just a method name which can be renamed and the issue is not about inserting data into database the issue is about connecting to database seems that - new NpgsqlConnection(_connectionString) fails to open connection to database since the error which is being provided is Failed to connect to 127.0.0.1:5432" with a System.Net.Sockets.SocketException (111): Connection refused this is not related to data insertion. Commented Jun 10, 2024 at 11:25
  • And the other thing that I'm wondering is that if it could be connection string why it has managed to create database after adding migration using the same connection string and this is where I'm getting confused Commented Jun 10, 2024 at 11:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.