使用 Postgresql 数据库更新 .NET7 项目中的数据库时收到“主机不能为空”错误

问题描述 投票:0回答:1
我想请你帮忙。我有一个连接到 Postgresql 数据库系统的 .NET7 项目,该项目在 Windows 上的 Visual Studio 中完美运行,但当我在新 Macbook 上的任何 IDE(Visual Studio、Rider)中打开它时,会出现一些问题。当我点击命令“dotnet ef database update”时,我收到错误“主机不能为空”

Build started... Build succeeded. System.ArgumentException: Host can't be null at Npgsql.NpgsqlConnectionStringBuilder.PostProcessAndValidate() at Npgsql.NpgsqlConnection.SetupDataSource() at Npgsql.NpgsqlConnection.set_ConnectionString(String value) at Npgsql.NpgsqlConnection..ctor(String connectionString) at Npgsql.NpgsqlConnection.CloneWith(String connectionString) at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlRelationalConnection.CloneWith(String connectionString) at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists(Boolean async, CancellationToken cancellationToken) at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists() at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists() at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Host can't be null
我多次检查了我的连接字符串,它已正确附加,我的 dotnet ef 版本是 7.0.11,所有 NuGet 包也与该版本的 EF 兼容:

<Project Sdk="Microsoft.NET.Sdk"> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.15" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.11"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" /> <PackageReference Include="xunit" Version="2.5.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.1"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> </ItemGroup>
我还尝试使用具有相同版本的 EF 和包的数据库构建一个简单的项目,并且“dotnet ef 数据库更新”命令在那里完美运行。

这是我的 AppDbContext.cs:

public class AppDbContext : DbContext { //...some code protected readonly IConfiguration _configuration; public AppDbContext(DbContextOptions options, IConfiguration configuration) : base(options) { _configuration = configuration; } protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseNpgsql(_configuration.GetConnectionString("DefaultConnection")); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); modelBuilder.HasSequence<int> ("BaggageTagsSequence").StartsAt(1).IncrementsBy(1).HasMax(999999).IsCyclic(); } }
...我不知道是否有必要,但这也是Program.cs

var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddDbContext<AppDbContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")) .LogTo(Console.WriteLine, LogLevel.Information)); builder.Services.AddSingleton<QueryExecutionService>(); builder.Services.AddControllers() .AddNewtonsoftJson() .AddJsonOptions(options => { options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); builder.Services.AddApplicationServices(builder.Configuration); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseMiddleware<ExceptionMiddleware>(); app.UseStatusCodePagesWithReExecute("/errors/{0}"); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); using var scope = app.Services.CreateScope(); var services = scope.ServiceProvider; var context = services.GetRequiredService<AppDbContext>(); var logger = services.GetRequiredService<ILogger<Program>>(); try { await context.Database.MigrateAsync(); await AppDbSeedData.SeedAll(context); } catch (Exception ex) { logger.LogError(ex, "An error occured during migration"); } app.Run();
所以现在我没有任何想法,有人知道哪里可能有问题吗?

.net postgresql entity-framework asp.net-core entity-framework-core
1个回答
0
投票
您的

appsettings.json

 文件中可能缺少“主机”属性

它应该看起来像这样:

"ConnectionStrings": { "DefaultConnection": "Host=your_host; Port=your_port; User Id=postgres; Password=your_password; Database=your_database_name" }
    
© www.soinside.com 2019 - 2024. All rights reserved.