Azure Database for PostgreSQL is a fully managed enterprise-grade PostgreSQL service that ensures advanced performance, security, and scalability for your applications. Whether you're building REST APIs, microservices, or data-heavy apps, PostgreSQL on Azure is a solid choice.

This guide will explain how to connect .NET applications to Azure Database for PostgreSQL and perform essential database operations, such as reading, inserting, updating, and deleting data, using C#.

Why dotConnect for PostgreSQL?

ORM support provided

Advanced ORM support

Fully supports EF Core, Dapper, NHibernate, LinqConnect, and other modern data access technologies for efficient and reliable data management.

Full ADO.NET compliance

Full ADO.NET compliance

Conforms to the latest ADO.NET standards and recent industry innovations for seamless and consistent integration with .NET applications.

Support for MySQL-specific data types

PostgreSQL-specific data types

Includes many PostgreSQL-specific features and fully supports all unique data types for accurate and complete data representation.

Secure connection ensured

Secure connection options

Provides robust security with support for SSL/SSH connections, connecting via proxy servers, embedded servers, and HTTP tunneling.

Integration with popular IDEs

IDE integration

Features native integration with Visual Studio and complete design-time support for accelerated development.

Priority support provided

Priority support & frequent updates

Includes priority support, detailed documentation, and regular updates for continuous improvement.

Download and activate dotConnect for PostgreSQL

You can start using dotConnect for PostgreSQL immediately with a 30-day free trial. Choose one of the following installation options:

30-day free trial version

dotnet add package Devart.Data.PostgreSql
Install-Package Devart.Data.PostgreSql

You can install the driver by using the Windows installer.

After you receive the license key, add it to your connection strings to connect to the data source.

Start using dotConnect for PostgreSQL in your project today with a free trial

Connect to Azure Database for PostgreSQL with Data Explorer

Let us connect to PostgreSQL in Azure with the help of the built-in Data Explorer. Click Tools, then select Connect to Database, and choose PostgreSQL as the data source.

Connect to a PostgreSQL database in the Azure cloud using the Data Explorer

Enter your server details and credentials. Click Connect.

Successful connection to a PostgreSQL database in Azure

Once connected, you can browse tables, execute queries, and manage data directly within the Data Explorer.

View the PostgreSQL data Azure in the Data Explorer

Connect and retrieve data from the database

Let us establish a connection with the Azure Database for PostgreSQL and then run a simple SELECT query to pull records from the Actor table. It confirms the connection is working correctly and the data is accessible.

Create the DatabaseConnection.cs class (connection strings)

The DatabaseConnection.cs class keeps connection details separate for better maintainability.

using Devart.Data.PostgreSql;

public static class DatabaseConnection
{
    public static PgSqlConnection CreateConnection()
    {
        string connectionString = "" +
            "Host=test.postgres.database.azure.com;" +
            "User Id=TestUser;" +
            "Password=TestPassword;" +
            "Port=5432;" +
            "Database=postgres;" +
            "Schema=public;" +
            "License key=**********";
        return new PgSqlConnection(connectionString);
    }
}

Connection strings

Property Description
Host or Server Host name or IP address of the PostgreSQL server
User Id User ID used to authenticate with PostgreSQL
Password Password for the user ID
Port Port on which the PostgreSQL server listens
Database Default database to use after connecting
Schema PostgreSQL schema to use
License key Your license key (only required when you use .NET Standard-compatible assemblies)

Update the connection string

Replace the placeholders in the connection string with your actual PostgreSQL database credentials. If you own a paid license of dotConnect for PostgreSQL, include the license key in the connection strings.

Add the code below to your Program.cs file.

using System;
using Devart.Data.PostgreSql;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!\n");

                string sql = "SELECT actor_id, first_name, last_name FROM actor ORDER BY actor_id LIMIT 10";
                using (PgSqlCommand command = new PgSqlCommand(sql, connection))
                using (PgSqlDataReader reader = command.ExecuteReader())
                {
                    Console.WriteLine("actor_id | first_name | last_name");
                    while (reader.Read())
                    {
                        int actorId = reader.GetInt32(0);
                        string firstName = reader.GetString(1);
                        string lastName = reader.GetString(2);
                        Console.WriteLine($"{actorId} | {firstName} | {lastName}");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Run the application

Build and run your application: select Start from the menu or click F5. It displays the data retrieved from the database.

Get data from the PostgreSQL database in Azure

Insert new records into Azure Database for PostgreSQL

Let's add a new row to the Actor table by executing an INSERT command. Use the below code.

using System;
using Devart.Data.PostgreSql;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!\n");

                // Insert a new actor
                string insertSql = "INSERT INTO actor (first_name, last_name, last_update) VALUES (@first, @last, NOW()) RETURNING actor_id, first_name, last_name";
                using (PgSqlCommand insertCmd = new PgSqlCommand(insertSql, connection))
                {
                    insertCmd.Parameters.AddWithValue("@first", "Emily");
                    insertCmd.Parameters.AddWithValue("@last", "Johnson");

                    using (PgSqlDataReader reader = insertCmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            int actorId = reader.GetInt32(0);
                            string firstName = reader.GetString(1);
                            string lastName = reader.GetString(2);
                            Console.WriteLine("New actor added:");
                            Console.WriteLine($"actor_id | first_name | last_name");
                            Console.WriteLine($"{actorId} | {firstName} | {lastName}");
                        }
                        else
                        {
                            Console.WriteLine("No actor was inserted.");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

See the results in the application:

Successfully inserted record in a PostgreSQL database in Azure

Update rows in Azure Database for PostgreSQL

Next, we want to update an existing record by changing the actor's first and last name. The following code shows how to build and run an UPDATE command from the application to modify data already stored in the database.

using System;
using Devart.Data.PostgreSql;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!\n");

                string updateSql = "UPDATE actor SET first_name = @first, last_name = @last, last_update = NOW() WHERE actor_id = @id";
                using (PgSqlCommand updateCmd = new PgSqlCommand(updateSql, connection))
                {
                    updateCmd.Parameters.AddWithValue("@first", "David");
                    updateCmd.Parameters.AddWithValue("@last", "Miller");
                    updateCmd.Parameters.AddWithValue("@id", 201);

                    int rowsAffected = updateCmd.ExecuteNonQuery();

                    if (rowsAffected > 0)
                    {
                        string selectSql = "SELECT actor_id, first_name, last_name FROM actor WHERE actor_id = @id";
                        using (PgSqlCommand selectCmd = new PgSqlCommand(selectSql, connection))
                        {
                            selectCmd.Parameters.AddWithValue("@id", 201);
                            using (PgSqlDataReader reader = selectCmd.ExecuteReader())
                            {
                                if (reader.Read())
                                {
                                    int actorId = reader.GetInt32(0);
                                    string firstName = reader.GetString(1);
                                    string lastName = reader.GetString(2);
                                    Console.WriteLine("Updated actor:");
                                    Console.WriteLine("actor_id | first_name | last_name");
                                    Console.WriteLine($"{actorId} | {firstName} | {lastName}");
                                }
                                else
                                {
                                    Console.WriteLine("Actor not found after update.");
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No actor found with actor_id: 201");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Our application displays the results:

Successfully updated record in a Azure Database for PostgreSQL

Delete rows from Azure Database for PostgreSQL

Finally, let us see how to delete the record. We are going to remove the actor we have just added to the database using the DELETE command with a condition.

using System;
using Devart.Data.PostgreSql;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!\n");

                string deleteSql = "DELETE FROM actor WHERE actor_id = @id";
                using (PgSqlCommand deleteCmd = new PgSqlCommand(deleteSql, connection))
                {
                    deleteCmd.Parameters.AddWithValue("@id", 201);

                    int rowsAffected = deleteCmd.ExecuteNonQuery();

                    if (rowsAffected > 0)
                    {
                        Console.WriteLine("Deleted actor with actor_id: 201");
                    }
                    else
                    {
                        Console.WriteLine("No actor found with actor_id: 201");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

The output in the application proves that the operation was successful.

Successfully deleted record from the PostgreSQL database table in Azure

Conclusion

This tutorial covers the essentials of connecting to and working with databases hosted in Azure Database for PostgreSQL from a .NET application. You can connect, query, insert, update, and delete records.

With these fundamentals in place, you can advance to more complex techniques and build richer, data-driven applications that take full advantage of PostgreSQL's power and flexibility in the cloud. Using dotConnect for PostgreSQL ensures a smooth, secure, and efficient connection experience during the development process.

FAQ

How do you install and activate dotConnect for PostgreSQL in a .NET project?
Install dotConnect for PostgreSQL either by running the Windows installer (EXE) or by adding the Devart.Data.PostgreSql NuGet package to your .NET project. Then, retrieve your activation key from the Devart Customer Portal and specify it in your connection string by using the License Key parameter to activate the provider and connect successfully.
How do you create a connection to PostgreSQL using dotConnect in C#?
Define a connection string that includes Host, User Id, Password, Database, and (if required) License Key. Then create a PgSqlConnection with this string and call Open() inside a try/catch block to verify the connection and handle any errors.
How do you enable SSL/TLS for secure PostgreSQL connections with dotConnect?
Add SslMode=Require and provide the certificate file paths (for example, CACert, Cert, and Key) in the connection string. Then create a PgSqlConnection with this string and call Open() to establish an encrypted SSL/TLS session.
Can you connect to PostgreSQL using Entity Framework Core and dotConnect?
Yes, you can connect to PostgreSQL using Entity Framework Core and dotConnect. You can either use Entity Developer to visually create an EF Core model from the database and generate the DbContext and entity classes, or run Scaffold-DbContext with a dotConnect connection string (including the License Key) to scaffold the DbContext and entities from an existing database.
Is it possible to connect to PostgreSQL using Visual Studio Server Explorer with dotConnect?
Yes. In Visual Studio Server Explorer, you can add a new Data Connection, select dotConnect for PostgreSQL as the data provider, enter your PostgreSQL connection details, test the connection, and then browse and work with database objects directly in the IDE.

Dereck Mushingairi

I'm a technical content writer who loves turning complex topics — think SQL, connectors, and backend chaos–into content that actually makes sense (and maybe even makes you smile). I write for devs, data folks, and curious minds who want less fluff and more clarity. When I'm not wrangling words, you'll find me dancing salsa, or hopping between cities.

dotConnect for PostgreSQL

Get an enhanced ORM-enabled data provider for PostgreSQL and develop .NET applications working with PostgreSQL data quickly and easily!

Try the 30-day trial of the full product. No limits. No card required. Start free trial