使用ASP.NET Core和dotConnect为PostgreSQL构建一个RESTful服务
本文探讨了RESTful架构以及我们如何使用ASP.NET Core和dotConnect for PostgreSQL实现RESTful服务。
REST这个词是Representational State Transfer的缩写。它是一种软件架构风格,为协助万维网架构的设计和开发而创建。REST定义了一套约束条件,界定了分布式超媒体系统,如网络,应该如何架构。Restful Web服务是基于HTTP的、简单的、轻量级的、快速的、可扩展的和可维护的服务,遵守REST架构风格。
REST架构风格将数据和功能视为通过统一资源标识符(URI)访问的资源。REST架构是一种客户-服务器范式,利用无状态的通信协议,通常是HTTP,用于服务器和客户之间的数据交换。在REST中,客户端和服务器通过一个定义好的标准化接口进行交互。
本文探讨了RESTful架构以及我们如何使用ASP.NET Core和dotConnect for PostgreSQL实现RESTful服务。在这篇文章中,我们将使用dotConnect forPostgreSQL连接到PostgreSQL,它是PostgreSQL的高性能和增强的数据提供者,建立在ADO.NET之上,可以在连接和断开的模式下工作。
前提条件
为了能够使用本文所演示的代码示例,你应该在你的系统中安装以下内容。
- Visual Studio 2019社区版
- PostgreSQL
- dotConnect for PostgreSQL
你可以从这里下载.NET Core。
你可以从这里下载Visual Studio 2019。
您可以从这里下载PostgreSQL。
您可以从这里下载dotConnect for PostgreSQL的试用版本。
创建数据库
您可以使用pgadmin工具创建一个数据库。要使用此启动此工具创建一个数据库,请按照下面的步骤进行。
- 启动pgadmin工具
- 展开 "服务器 "部分
- 选择数据库
- 右击并点击创建->数据库...
- 指定数据库的名称,并将其他选项保留为其默认值
- 单击 "保存 "以完成该过程
创建一个数据库表
选择并展开你刚刚创建的数据库
选择模式->表
右键单击表,选择创建->表...
图1
指定表的列,如下图2所示。
图2
下面给出了表的脚本供你参考。
MS SQL
CREATE TABLE public."Product"
(
"Id" bigint NOT NULL,
code character(5) COLLATE pg_catalog."default" NOT NULL,
name character varying(100) COLLATE pg_catalog."default" NOT NULL,
" quantity" bigint NOT NULL,
CONSTRAINT "Product_pkey" PRIMARY KEY ("Id")
)
我们将在本文的后续章节中使用该数据库,以展示我们如何在ASP.NET Core中使用Postgresql和dotConnect工作。
dotConnect for PostgreSQL的特点和优势
dotConnect for PostgreSQL的一些主要特点包括如下。
- 高效能
- 完全管理的代码
- 无缝部署
- 支持最新版本的PostgreSQL
- 支持.NET框架、.NET核心及.NET Compact框架
- 支持连接和断开的模式
- 支持PostgreSQL的所有数据类型
- 改进数据绑定能力
- 支持监控查询的执行
您可以在此了解更多关于dotConnect for PostgreSQL的功能。以下是dotConnect for PostgreSQL的一些优点。
- 能够编写高效及优化的代码
- 对ADO.NET的全面支持
- 支持Entity Framework
- 支持LinqConnect
- 支持连接和断开的模式
介绍一下dotConnect for PostgreSQL
dotConnect for PostgreSQL是一个建立在ADO.NET技术上的高性能PostgreSQL数据提供者。您可以利用新的方法来构建应用架构,提高生产力,并使创建数据库应用变得更容易。它的前身是PostgreSQLDirect.NET,是一个改进的PostgreSQL的数据提供者,为建立基于PostgreSQL的数据库应用提供了一个全面的解决方案。
作为一个适用于PostgreSQL的可扩展的数据访问解决方案,dotConnect for PostgreSQL在设计上具有高度的灵活性。您可以在WinForms、ASP.NET、ASP.NET Core、两层、三层及多层应用程序中有效地使用它。dotConnect for PostgreSQL数据提供者可被用作一个强大的ADO.NET数据源或一个有效的应用程序开发框架,这取决于您选择的版本。
在Visual Studio 2019中创建一个新的ASP.NET Core Web API项目
一旦您安装了使用dotConnect for PostgreSQL所需的必要软件和/或工具,请按照先前文章《使用Entity Framework Core和Entity Developer处理查询》中提到的步骤,在Visual Studio 2019中创建一个新的ASP.NET Core 5.0项目。
安装NuGet包
要在ASP.NET Core 5中使用dotConnect for PostgreSQL,您应该在您的项目中安装以下包。
Devart.Data.PostgreSql
您有两个选择来安装此包:通过NuGet包管理器或通过包管理器控制台窗口运行以下命令。
PM> 安装-包 Devart.Data.PostgreSql
为PostgreSQL编程dotConnect
本节将讲述您如何使用dotConnect for PostgreSQL。
创建模型
创建一个名为Product的类,其中包含以下代码。
C#
public class Product
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
这是我们的模型类,我们将用它来存储和检索数据。
创建RESTful端点
在这个项目中创建一个新的控制器类,并将其命名为ProductController。现在用下面的代码替换生成的代码。
C#
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
[HttpGet]
public List<Product> Get()
{
throw new NotImplementedException();
}
[HttpPost]
public void Post([FromBody] Product product)
{
throw new NotImplementedException();
}
[HttpPut]
public void Put([FromBody] Product product)
{
throw new NotImplementedException();
}
}
正如你所看到的,ProductController类中有三个RESTful端点。注意控制器方法中HTTP动词的用法。我们将很快实现每个控制器方法。
使用dotConnect for PostgreSQL插入数据
下面的代码片段可以用来插入数据到我们之前创建的PostgreSQL数据库的产品表中。
C#
[HttpPost]
public int Post([FromBody] Product product) {
try {
using(PgSqlConnection pgSqlConnection =
new PgSqlConnection("User
Id=postgres;Password=sa123#;host=localhost;database=postgres;")) {
using(PgSqlCommand cmd = new PgSqlCommand()) {
cmd.CommandText = "INSERT INTO public.product
(id, code, name, quantity)
VALUES (@id, @code,@name, @quantity)";
cmd.Connection = pgSqlConnection;
cmd.Parameters.AddWithValue("id", product.Id);
cmd.Parameters.AddWithValue("code", product.Code);
cmd.Parameters.AddWithValue("name", product.Name);
cmd.Parameters.AddWithValue("quantity", product.Quantity);
if (pgSqlConnection.State != System.Data.ConnectionState.Open)
pgSqlConnection.Open();
return cmd.ExecuteNonQuery();
}
}
}
catch
{
throw;
}
}
使用dotConnect for PostgreSQL读取数据
使用dotConnect读取数据是相当直接的。下面的代码片段说明了您如何使用dotConnect for PostgreSQL从产品数据库表中读取数据。
C#
[HttpGet]
public List <Product> Get()
{
try {
List <Product> products = new List < Product > ();
using(PgSqlConnection pgSqlConnection =
new PgSqlConnection("User
Id=postgres;Password=sa123#;host=localhost;database=postgres;"))
{
using(PgSqlCommand pgSqlCommand = new PgSqlCommand()) {
pgSqlCommand.CommandText = "Select * From public.Product";
pgSqlCommand.Connection = pgSqlConnection;
if (pgSqlConnection.State != System.Data.ConnectionState.Open)
pgSqlConnection.Open();
using(PgSqlDataReader pgSqlReader = pgSqlCommand.ExecuteReader()) {
while (pgSqlReader.Read()) {
Product product = new Product();
product.Id = int.Parse(pgSqlReader.GetValue(0).ToString());
product.Code = pgSqlReader.GetValue(1).ToString();
product.Name = pgSqlReader.GetValue(2).ToString();
product.Quantity =
int.Parse(pgSqlReader.GetValue(3).ToString());
products.Add(product);
}
}
}
}
return products;
}
catch
{
throw;
}
}
使用dotConnect for PostgreSQL修改数据
下面的代码列表说明了您如何利用dotConnect for PostgreSQL来修改一个现有的记录。
C#
[HttpPut("{id}")]
public void Put([FromBody] Product product) {
try {
using(PgSqlConnection pgSqlConnection =
new PgSqlConnection("User
Id=postgres;Password=sa123#;host=localhost;database=postgres;")) {
using(PgSqlCommand cmd = new PgSqlCommand()) {
cmd.CommandText = "UPDATE Product SET Name = @name WHERE Id = @id";
cmd.Parameters.AddWithValue("id", product.Id);
cmd.Parameters.AddWithValue("name", product.Name);
cmd.Connection = pgSqlConnection;
if (pgSqlConnection.State != System.Data.ConnectionState.Open)
pgSqlConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch
{
throw;
}
}