本文主要介绍EFCore,以及NpgSql的基本使用方法。
使用EFCore
使用EFCore首先在NuGet包管理器中添加对应的依赖,如postgres数据库对应的Npgsql.EntityFrameworkCore.PostgreSQL包,mysql数据库对应的MySql.Data.EntityFrameworkCore包。
创建数据库
首先使用以下sql语句建立一张数据表:
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT '',
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
)
id为account表的主键。
数据库配置信息
采用Entity Framework Core进行数据库的操作,目标框架为 .net Core,因此在appsettings.json文件中添加数据库的信息:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": { "PgContext": "host= ;port= ;database=; user id= ;password=" }
}
创建Model
[Table("account", Schema = " ")]
public class Account
{
[Column("id")] public int? Id { get; set; }
[Column("userId")] public string UserId { get; set; }
[Column("pasword")] public string Password { get; set; }
[Column("username")] public string Username { get; set; }
}
其中,注解Table声明了对应的模式下(Schema)的数据表,将model与数据表进行了对应。注解Column将每一个属性与数据表中的列进行对应。
创建一个DbContext
public class PgContext : DbContext
{
public PgContext(DbContextOptions<PgContext> options) : base(options) { }
public virtual DbSet<Account> Accounts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseNpgsql(Configuration.GetConnectionS