【问题标题】:ASP.NET Core MVC with pgadmin show the table of database带有 pgadmin 的 ASP.NET Core MVC 显示数据库表
【发布时间】:2021-08-12 08:59:31
【问题描述】:

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

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

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

【问题讨论】:

标签: postgresql entity-framework orm asp.net-core-mvc pgadmin


【解决方案1】:

右键单击项目解决方案选择管理 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2019-05-04
      • 2021-10-25
      相关资源
      最近更新 更多