整地支持外键、联合、视图、触发器和存储过程(并支持多种语言开发存储过程)。它支持了大多数的SQL:2008标准的数据类型,包括整型、数值值、布尔型、字节型、字符型、日期型、时间间隔型和时间型,它也支持存储二进制的大对像,包括图片、声音和视频。PostgreSQL对很多高级开发语言有原生的编程接口,如C/C++、Java、.Net、Perl、Python、Ruby、Tcl 和ODBC以及其他语言等,也包含各种文档
以上介绍来自 PostgreSQL 中文社区:http://www.postgres.cn/v2/about,本人公司的主要业务也是基于 .NetCore+MySql+PostgreSQL,在使用 PostgreSQL 的过程中,发现 PostgreSQL 真的是一个非常强大的数据库,对我们的业务带来非常大的帮助,希望大家都能深入的了解和使用 PostgreSQL
2.1 首先还是在项目中引用 Npgsql.EntityFrameworkCore.PostgreSQL 包
2.2 编写上下文对象 NPgSqlForumContext
public class NPgSqlForumContext : DbContext
{
public NPgSqlForumContext(DbContextOptions<NPgSqlForumContext> options) : base(options) { }
public DbSet<Topic> Topics { get; set; }
public DbSet<Post> Posts { get; set; }
}
有没有发现,上下文对象 NPgSqlForumContext 的结构和上面的 MySqlForumContext 几乎是一模一样的
2.3 在配置文件中增加 PostgreSQL 的连接字符串
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Mysql.Forum": "server=127.0.0.1;port=3406;uid=root;pwd=root;database=Forum;",
"Pgsql.Forum": "server=127.0.0.1;port=5432;uid=postgres;pwd=postgres;database=Forum;"
}
}
注意:PostgreSQL 的侦听的默认端口是:5432
2.4 在 Startup.cs 中初始化上下文对象
public void ConfigureServices(IServiceCollection services)
{
// MariaDB/MySql 上下文初始化
services.AddDbContext<MySqlForumContext>(options =>
{
var connectionString = this.Configuration["ConnectionStrings:Mysql.Forum"];
options.UseMySql(connectionString);
});
// PostgreSQL 上下文初始化
services.AddDbContext<NPgSqlForumContext>(options =>
{
var connectionString = this.Configuration["ConnectionStrings:Pgsql.Forum"];
options.UseNpgsql(connectionString);
});
...
}
2.5 创建 Migrations for PostgreSQL 对象
- 这里创建 Migrations 的方式和上面的创建 Migrations for MariaDB/MySql 的方式是一样的,在项目包管理器控制台中输入以下命令,创建 Migrations 对象后直接创建数据库
Add-Migration PostgreSQL.Forum.v1 -Context NPgSqlForumContext
Update-Database -Context NpgSqlForumContext
== 注意:这里的创建数据库命令和上面创建 MariaDB/MySql 的命令有一点小小的不同 ==
因为我们现在是在一个项目里面使用多个上下文对象,在创建 Migrations 的时候, EF 会自动查找匹配的 Context ,但是,由于使用了多个 Context,在执行命令时,必须指定 -Context NpgSqlForumContext,否则,将抛出 More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands. 的异常。
- 打开 PostgreSQL 管理工具,发现数据库 forum 已经成功创建,表结构和 MariaDB/MySql 中创建的 forum 数据库表完全一致,使用的都是同一个实体业务对象 Topic/Post
到这里,我们已经完成了使用 EFCore 连接到 PostgreSQL 的过程,在 PostgreSQL 中,由于没有指定 Schema ,所以默认数据表会被放在 Schema public 下面,有关更多 PostgreSQL 的 Schema ,请移步官网进一步了解,如果希望在创建数据库的过程中指定 Schema ,可以在实体对象 Topic中应用特性 TableAttribute 进行标记即可,也可以手动修改 Migrations 文件,像下面这样
[Table("topic",Schema ="blogs")]
public class Topic
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime CreateTime { get; set; }
public ICollection<Post> Posts { get; set; }
}
- 手动修改 Migrations 文件 Migrations/20190119035709_PostgreSQL.Forum.v1.cs
// 代码片段,仅需要增加指定 schema:"blogs" 即可
migrationBuilder.CreateTable(
name: "Topics",
schema: "blogs",
columns: table =>