右键单击项目解决方案选择管理 Nuget 包并安装以下包:
Npgsql.EntityFrameworkCore.PostgreSQL
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
安装时版本可能会有所不同,请注意兼容性。
安装完成后,进入 Startup.cs。在 ConfigureServices 方法中,我们需要将 PostgreSQL 添加到项目中添加您的数据库上下文(在我的情况下为 MyWebApiContext)和连接字符串名称(在 appsettings.json 中添加 ConnectionString)(在我的情况下为 MyWebApiConection)。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddEntityFrameworkNpgsql().AddDbContext<MyWebApiContext>(opt =>
opt.UseNpgsql(Configuration.GetConnectionString("MyWebApiConection")));
}
配置数据库连接
在appsetting.json中,我们需要先写好PostgreSQL用户id、密码、服务器、端口和代码创建的数据库名。
"ConnectionStrings": {
"MyWebApiConection": "User ID =postgres;Password=1234;Server=localhost;Port=5432;Database=testDb;
Integrated Security=true;Pooling=true;"
}
连接字符串添加在appsettings.json的顶部,(appsettings.json的完整视图)。
{
"ConnectionStrings": {
"MyWebApiConection": "User ID =postgres;Password=1234;Server=localhost;Port=5432;Database=testDb;Integrated Security=true;Pooling=true;"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}
创建模型
创建一个文件夹并将其命名为模型(可能是实体),添加组、用户和上下文模型。
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
// from the group model (Entity framework will connect the Primarykey and forign key)
public Group Group { get; set; }
public int GroupId { get; set; }
}
现在,创建一个 DbContext(在我的例子中,我将其命名为 MyWebApiContext)。此数据库上下文继承自 DbContext。
DbContext 错误:检查它可能未安装的 entityFramework。
MyWebApiContext > 在构造函数中添加数据库上下文名称。
public class MyWebApiContext:DbContext
{
public MyWebApiContext(DbContextOptions<MyWebApiContext> options):base(options) { }
public DbSet<User> Users { get; set; }
public DbSet<Group> Groups { get; set; }
}
}
然后进行迁移
PM> enable-migrations
PM> add-migration initial
PM> update-database