Black Friday is here! Get up to 30% off on Devart products!
ends in   {{days}}
Days
{{timeFormat.hours}}
:
{{timeFormat.minutes}}
:
{{timeFormat.seconds}}

How to connect to PostgreSQL in .NET with C#

Database connectivity is essential since no application can function properly without a way to store and manage data, allowing for the insertion and retrieval of information when needed. PostgreSQL stands out as a favored option for application development because of its open-source nature, rich feature set, reliability, and excellent performance. With the backing of a vast developer community and comprehensive documentation, PostgreSQL ensures that help is always within reach.

For developers working on .NET applications, integrating PostgreSQL as the backend offers a reliable, scalable, and cost-effective solution that adapts to evolving needs. In this article, we'll delve into some of the most effective techniques for establishing a connection between your .NET application and PostgreSQL.

Why dotConnect for PostgreSQL?

dotConnect for PostgreSQL is the ideal data provider for all PostgreSQL-related operations. It offers on-the-fly connector creation and flexible configuration, seamless integration into Visual Studio, and enhanced ORM support.

Download Now dotConnect for PostgreSQL

Requirements

The following prerequisites are necessary to follow this guide:

  • Visual Studio 2022: This is our IDE of choice. If you don't have it on your machine, you can visit the official website to download and install the free Community Edition.
  • dotConnect for PostgreSQL: A high-performance data provider for PostgreSQL with enhanced ORM support and database connectivity features.
  • Entity Developer: An ORM designer for .NET ORM Frameworks with powerful code generation (more on this later).
  • DvdRental sample database: The sample database from the official PostgreSQL documentation.

Download and activate dotConnect for PostgreSQL

Visit the dotConnect for PostgreSQL download page. You can choose the free trial or the full version of dotConnect for PostgreSQL. The trial version gives you 30 days to explore all features and doesn't require a license key for activation, but it can't be used for deploying commercial projects.

Download and install the trial version

To use the trial version, download and install dotConnect for PostgreSQL on your machine. No license key is required for the trial, and you can start exploring the product immediately.

Purchase and access the full version

If you're ready to purchase the full version, click Buy Now to add it to your cart and complete the purchase.

After purchasing the full version, go to Your Licenses in the user menu. There you'll have a list of your licenses, including your dotConnect for PostgreSQL purchase.

To view your license details and find the activation key, click Details next to your dotConnect for PostgreSQL license.

Your Licenses page with purchased products

Download the full version

Click Download Product Versions to view the list of available product versions. Select the most recent version and download the installer.

Available versions of dotConnect for PostgreSQL

Run the downloaded file and follow the on-screen instructions to install dotConnect for PostgreSQL on your machine. This process installs the software and activates all features associated with your license key.

Create .NET Project

The first thing we'll do is set up a new .NET Application project. Open Visual Studio you installed and click Create New Project. In the Search Template field, type ASP.NET Core Web Application and click the corresponding search result. Give your project a name. For example, ours is going to be called PostgreSQL_ASP.NET. Then select .NET 8 as the target framework and
click Create.

Next, we are going to install dotConnect for PostgreSQL to our project via the NuGet Package Manager in Visual Studio. On the taskbar, click Tools, then navigate to NuGet Package Manager > Manage NuGet Packages for Solution.

NuGet Package Manager

The NuGet Package Manager page opens. Click Browse, search for Devart.Data.PostgreSQL, and select it once found. Then, select your project and click Install.

Find the project

When you run the application by clicking F5 the scaffolded web page appears. To configure your PostgreSQL database, follow the steps to create a test database named dvdrental from Load PostgreSQL Sample Database. After successfully configuring the database, you can move on to the next step. Now, let us set up our Database connection class. Right-click your project, go to Add, and click Class.

Add the class

After that, right-click and add again, then add the Actor.cs class. Copy this piece of code inside that class:

  public class Actor
  {
      public int ActorId { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public DateTime LastUpdate { get; set; }
  }

Connect to PostgreSQL

Great now, let's add a method to our DatabaseConnectionClass, copy this piece of code into your class:

public static DataTable GetActorTable()
 {
	try
	{
         // Open a connection to the PostgreSQL database
         string connectionString = "" +
            "Server=127.0.0.1;" +
            "Port=5432;" +
            "UserId=TestUser;" +
            "Password=TestPassword;" +
            "Database=dvdrental;" +
            "Schema=public;" +
            "LicenseKey=**********";
         DataTable table;
         using (var connection = new Devart.Data.PostgreSql.PgSqlConnection(connectionString))
         {
             connection.Open();
             string query = "SELECT * FROM actor LIMIT 10;";
             PgSqlDataAdapter adapter = new Devart.Data.PostgreSql.PgSqlDataAdapter(query, connection);
             DataSet dataSet = new DataSet();
             adapter.Fill(dataSet, "actor");
             table = dataSet.Tables["actor"];
             connection.Close();
         }
         return table;

       }
	catch (Exception ex)
	{
         Console.WriteLine(ex.Message);
         return null;
       }
 }

Don't forget to use Devart.Data.PostgreSql at the top of your file and your actual user and password.

Connect using the SSL/TLS connection

You can also connect to a PostgreSQL database with the help of the SSL/TLS connection. This code will show you how:

public static DataTable GetActorTableUsingSSL()
{
    try
    {
        // Open a SSL connection to the PostgreSQL database
        DataTable table = new DataTable();
        Devart.Data.PostgreSql.PgSqlConnectionStringBuilder pgCSB = new Devart.Data.PostgreSql.PgSqlConnectionStringBuilder();
        pgCSB.Server = "localhost";
        pgCSB.Port = 5432;
        pgCSB.UserId = "TestUser";
        pgCSB.Password = "TestPassword";
        pgCSB.Schema = "public";
        pgCSB.MaxPoolSize = 150;
        pgCSB.Database = "dvdrental";
        pgCSB.ConnectionTimeout = 30;
        pgCSB.SslMode = SslMode.Require;
        pgCSB.SslCACert = "/root.crt";
        pgCSB.SslKey = "/server.key";
        pgCSB.SslCert = "/server.crt";
        pgCSB.LicenseKey = "**********";
        PgSqlConnection myConnection = new PgSqlConnection(pgCSB.ConnectionString);

        PgSqlCommand command = new Devart.Data.PostgreSql.PgSqlCommand("SELECT * FROM actor LIMIT 10;", myConnection);
        myConnection.Open();
        using (PgSqlDataReader reader = command.ExecuteReader())
        {
            table.Load(reader);
        }
        myConnection.Close();
        return table;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return null;
    }
}

Here, we have defined the following parameters:

  • SslOptions.CACert - the location of your authority certificate.
  • SslOptions.Cert - the location of your client certificate.
  • SslOptions.Key - the location of your client private key.

This way, the communication between the PostgreSQL client and server becomes secure as you've encrypted it with SSL.

Now, we need to be able to visualize the data we have just returned. In Solution Explorer, click Controllers, select Add New Class, and add the ActorsController class. Inside the PostgreSQL_ASP.NET_ASP.NET.Controllers namespace, modify the class using this code:

[ApiController]
[Route("api/[controller]/[action]")]
public class ActorsController : ControllerBase
{
    [HttpGet]
    public IEnumerable GetActors()
    {
        List actorList = new();
        DataTable dataTable = DatabaseConnectionClass.GetActorTable();

        foreach (DataRow row in dataTable.Rows)
        {
            Actor obj = new Actor
            {
                ActorId = Convert.ToInt32(row["actor_id"]),
                FirstName = Convert.ToString(row["first_name"]),
                LastName = Convert.ToString(row["last_name"]),
                LastUpdate = Convert.ToDateTime(row["last_update"])
            };
            actorList.Add(obj);
        }

        return actorList;
    }
}

Check out our comprehensive guide on PostgreSQL Connection Strings for a variety of connection scenarios.

When you run your project, click the dropdown for GetActors, select Try it now, and then click Execute. After executing, we can see the list we want:

The desired list

Great! We have successfully established the connection to our PostgreSQL database.

Connect with EF Core through Entity Developer

Another way to connect to a PostgreSQL database is through Entity Developer. To do it, download a free trial. It is provided for 30 days and offers all the functionality for proper testing under the actual workload. Then download, install, and open Entity Developer. And navigate to File > New Model.

New model

In the model pane, click Entity Model under Devart Entity Framework. In the Entity Developer Model wizard, select Database first and click Next.

Entity model

The Setup data connection properties window pops up. Fill in the details of your PostgreSQL database connection as follows and ener your own ID and password, which were configured while setting up PostgreSQL.

Connection properties

After clicking Next, select Generate From Database and click Next.

Connection properties

Next, choose the database objects you want to include to the model. You can select all, but since we're using the actor table, we'll select it.

Select the required objects

Having clicked Next, you will be asked to set up naming rules. This will define the naming convention you want the property names in the database object to follow. We'll leave it by default and click Next.

Set up naming rules

Configure the model properties, select the required framework from Target Framework and click Next

Select the target framework

After that, choose the model diagram contents. For this tutorial, we'll use All Entities, so select this option and click Next.

Choose the model diagram contents

On the Code Generation Templates page, choose templates for the model. Here, you can define different parameters you want the object to follow. We'll use the default settings for this tutorial.

Choose templates for the model

Click Next and your model will be fully created.

The created model

Connect with EF Core using Scaffold-DbContext

It's also possible to connect our .NET application to a PostgreSQL database via EF (Entity Framework) Core. Let's see how to
implement it.

First, we need to add a separate project to our solution to illustrate the case. Right-click the current PostgreSQL_ASP.NET solution in the Visual Studio Solution Explorer and go to Add > New project.

Create a new project

This additional project, in our case, is called PostgreSQL_EF_Core_ASP.NET, and we added it in the same way as we did at the beginning of this tutorial. Right-click it and set it as a startup project.

First, ensure you have EF Core Tools installed in your development environment. You can install them globally using the .NET CLI from the command line:

dotnet tool install --global dotnet-ef

Next, open NuGet Package Manager for the project in Visual Studio, select Devart.Data.PostgreSQL.EFCore, and click Install.

Select the project

To install Scaffold-DbContext via the Package Manager Console, open Visual Studio, navigate to Tools > Package Manager Console, and select PostgreSQL_EF_Core_ASP.NET as the project. When the console opens, execute the following command:

Install-Package Microsoft.EntityFrameworkCore.Tools

Install the package

Once installed, we can use Scaffold-DbContext to generate DbContext and entity classes for our PostgreSQL database. Execute the following command from the Package Manager Console:

Scaffold-DbContext "Server=127.0.0.1;Port=5432;UserId=TestUser;Password=TestPassword;Database=dvdrental;Schema=public;LicenseKey=**********" Devart.Data.PostgreSql.Entity.EFCore

Remember to provide your relevant credentials for your User ID and password. After that, dbContext will be renamed to DvdrentalContext, and the table entity classes should be generated. You can see them in your Solution Explorer.

Generated entity classes

Let's use the Actors class again. We'll query this entity table using LINQ. Right-click the PostgreSQL_EF_Core_ASP.NET project, select the option to add a class, and add DatabaseConnectionClass as we did earlier. Then copy this code into the class:

public class DatabaseConnectionClass
 {
     private readonly DvdrentalContext _context;

     public DatabaseConnectionClass()
     {
         _context = new DvdrentalContext();
     }

     public List GetActors()
     {
         return _context.Actors.Take(10).ToList();
     }
 }

We have used Dvdrentalcontext to get the entity of actors and returned it to a list. Just like before, we need a way to visualize our data, so add a new class called ActorsController into the Controllers folder. Modify the class with the code below inside the PostgreSQL_EF_Core_ASP.NET.Controllers namespace:

public class DatabaseConnectionClass
[ApiController]
    [Route("api/[controller]/[action]")]
    public class ActorsController : ControllerBase
    {
        private readonly DatabaseConnectionClass _context;

        public ActorsController()
        {
            _context = new DatabaseConnectionClass();
        }

        [HttpGet]
        public IEnumerable GetActors()
        {
            return _context.GetActors();
        }
    }

Modify the class

Run your application by clicking F5, go to the GetActors endpoint, click Try it out and Execute. You will see your query results in the response body as was shown earlier.

GetActors endpoint

For more information on working with EF Core, refer to How to Use Entity Framework (EF) Core with PostgreSQL, which includes instructions on performing the INSERT, UPDATE, and DELETE operations.

More advantages of dotConnect for PostgreSQL

Simplified Development: Work directly with PostgreSQL from your application without the need for separate libraries.

Effortless ORM Integration: Easily build ORMs using the Entity Developer tool, boost productivity and code maintainability.

Enhanced Web Features: Leverage ASP.NET providers for features like user roles, session management, and membership.

Optimized Performance: Gain maximum speed through PostgreSQL-specific optimizations to ensure your application
runs smoothly.

Detailed Insights: Track database activity for each component with the free dbMonitor tool, identify and fix issues.

Robust Security: Protect your data with various encryption options, secure connections (SSL, SSH), and other means.

Video tutorial: How to Connect a .NET Console Application to a PostgreSQL Database

Conclusion

This article provides comprehensive guides on connecting .NET applications to PostgreSQL databases using several approaches. We've covered various connection techniques, such as secure SSL/TLS connections and implementing Entity Framework Core with Scaffold-DbContext.

By utilizing Devart's dotConnect for PostgreSQL, you can significantly enhance your application's efficiency, achieving faster, smoother, and simpler performance across all tasks. Try out a free trial to experience seamless database connectivity, optimized performance, and robust security for your .NET projects!

dotConnect for PostgreSQL

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