ASP.NET 核心 MVC 与 pgadmin 显示 table 数据库

ASP.NET Core MVC with pgadmin show the table of database

我是新来的,我在ASP.NET MVC中使用ADO.NET来连接模型和数据库。

现在想用ASP.NET Core MVC连接Postgresql,但是不知道怎么办。

我使用“工具”下的“连接数据库”,然后我想从我的数据库中显示我的table,我应该怎么做?

您可能应该使用 Entity Framework 核心 ORM。它有几个用于 PostgreSQL 的数据库提供程序:Npgsql 和 devart – Peter Riesz

右键单击项目解决方案select管理 Nuget 包并安装以下包:

Npgsql.EntityFrameworkCore.PostgreSQL
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools

安装时版本可能不同,注意兼容性。

安装后,前往Startup.cs。在 ConfigureServices 方法中,我们需要将 PostgreSQL 添加到项目中 添加您的数据库上下文(在我的例子中是 MyWebApiContext)和连接字符串名称(ConnectionString 添加到 appsettings.json)(在我的例子中是 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 的顶部,(appsetting.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