Md *_*ron 6

如何在 ASP.NET Core 中使用 postgres SQL 建立数据库连接?

有两种方法可以将postgresql数据库与asp.net core项目一起添加。

使用以下方式:

  • ADO.net connection provider
  • Nuget extension: Npgsql.EntityFrameworkCore.PostgreSQL

ADO.net connection provider

这里只需要连接构建器类,它将在数据库服务器上NpgsqlConnection执行您的连接构建器类。请参阅下面的示例:sqlPostgre sql

C# ASP.NET Core & Postgre SQL Ado.net example:

  NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;Password=pwd;Database=postgres;");
    
    conn.Open();
    
    // Passing PostGre SQL Function Name
    NpgsqlCommand command = new NpgsqlCommand("EXE GetEmployeePrintInfo", conn);
    
    // Execute the query and obtain a result set
    NpgsqlDataReader reader = command.ExecuteReader();
    
    // Reading from the database rows
    List<string> listOfManager = new List<string>();

    while (reader.Read())
    {
        string WSManager = reader["WSManager"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
        listOfManager.Add(WSManager);
    }
    reader.Close();

    command.Dispose();
    conn.Close();
Run Code Online (Sandbox Code Playgroud)

Npgsql.EntityFrameworkCore.PostgreSQL:

您必须将使用添加Nuget extension到项目引用中。许多数据库提供商都具有此功能。只需按照以下步骤操作即可manage Nuget PackagesVisual studioEntity framework corevisual studio

在此输入图像描述

ConfigureServices in startup.cs: 成功添加后,Nuget package您必须在项目下更新以下ConfigureServices代码startup.cs

  NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;Password=pwd;Database=postgres;");
    
    conn.Open();
    
    // Passing PostGre SQL Function Name
    NpgsqlCommand command = new NpgsqlCommand("EXE GetEmployeePrintInfo", conn);
    
    // Execute the query and obtain a result set
    NpgsqlDataReader reader = command.ExecuteReader();
    
    // Reading from the database rows
    List<string> listOfManager = new List<string>();

    while (reader.Read())
    {
        string WSManager = reader["WSManager"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
        listOfManager.Add(WSManager);
    }
    reader.Close();

    command.Dispose();
    conn.Close();
Run Code Online (Sandbox Code Playgroud)

Note:如果您需要任何示例entityframeworkPostgre SQL 实现,可以查看此处

如需进一步帮助,您可以在此处查看官方文档。希望它能为您提供相应的指导。