建立通用 AppHost项目
先在 Program.cs中配置好数据库连接
builder.AddNpgsqlDbContext<TasksContext>("Default-PostgreSQL", configureDbContextOptions: option =>
{
});
然后在 appsettings.json中添加数据库连接字符串
{
// ...
"ConnectionStrings": {
"Default-PostgreSQL": "..."
}
}
编写 DbContext 如下
using Microsoft.EntityFrameworkCore;
public class ExampleContext(DbContextOptions options) : DbContext(options)
{
public DbSet<ExampleRecordType> Records { get; set; }
}
使用 dotnet-tools初始化数据库(建立初始化迁移)
dotnet ef migrations add InitialCreate
dotnet database update