1

我正在尝试通过我的 .NET Core 应用程序创建和使用 PostgreSQL 数据库。我正在使用 Npgsql 提供的 Entity Framework Core,并且我将采用“代码优先”的方法。但是,当我尝试生成数据库(使用迁移或“Database.EnsureCreated()”方法)时,我总是得到同样的错误:

Npgsql.NpgsqlException(0x80004005):连接时出现异常---> System.Net.Sockets.SocketException(10061):连接被拒绝。

我在 Windows 和 Linux 上都试过了,我得到了相同的结果。

我为我的项目添加的包是:

  • Npgsql.EntityFrameworkCore.PostgreSQL版本 3.1.3
  • Microsoft.EntityFrameworkCore.Design版本 3.1.3

我的项目使用 .NET Core 3.1

这是我的代码:

using Microsoft.EntityFrameworkCore;
using System;

namespace PostgresTest {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Hello World!");
        }
    }
    public class PeopleContext : DbContext {
        public DbSet<Person> People { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options.UseNpgsql("Host=localhost;Database=postgres;Port=5432;Username=postgres;Password=12345678");
    }
    public class Person {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

编辑:需要明确的是,当我使用迁移时,创建迁移本身会成功,但是当我之后使用“数据库更新”命令时,我仍然会收到上述错误。

4

2 回答 2

2

从https://www.enterprisedb.com/downloads/postgres-postgresql-downloads下载 PostgreSQL 服务器并根据您的配置更新您的连接字符串。
更多https://code-maze.com/configure-postgresql-ef-core/

于 2020-04-15T06:24:43.270 回答
0

我认为你的连接不好。尝试HOST改变SERVER

protected override void OnConfiguring(DbContextOptionsBuilder options)=>
                 //options.UseNpgsql("Host=localhost;Database=postgres;Port=5432;Username=postgres;Password=12345678"); 
    options.UseNpgsql("Server=localhost;Database=postgres;Port=5432;Username=postgres;Password=12345678");
于 2020-08-06T21:23:40.243 回答