我正在尝试在.NET Core应用程序中创建和使用PostgreSQL数据库。我正在使用Npgsql提供的Entity Framework Core,并且打算采用“代码优先”的方法。但是,当我尝试生成数据库(使用迁移或“ Database.EnsureCreated()”方法)时,总是出现相同的错误:
Npgsql.NpgsqlException(0x80004005):连接时发生异常 ---> System.Net.Sockets.SocketException(10061):连接被拒绝。
我在Windows和Linux上都尝试过,并且得到了相同的结果。
我为我的项目添加的软件包是:
我的项目使用.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; }
}
}
Edit:明确地说,当我使用迁移时,创建迁移本身会成功,但是当我随后使用“数据库更新”命令时,仍然会遇到上述错误。
从https://www.enterprisedb.com/downloads/postgres-postgresql-downloads下载PostgreSQL服务器并根据您的配置更新您的连接字符串。 更多https://code-maze.com/configure-postgresql-ef-core/