gpt4 book ai didi

Receiving weird host can't be null error with ef core(接收奇怪的主机不能为空错误的ef核心)

转载 作者:bug小助手 更新时间:2023-10-24 19:37:03 24 4
gpt4 key购买 nike



I have recently installed the EF Core 3.1.6 on a home project using postgresql.

我最近在一个使用PostgreSQL的家庭项目上安装了EF Core 3.1.6。


I have the connection string, and can add migrations easily with the Package Manager Console. If I run my application the Database.Migrate() will migrate the migrations easily. However if I attempt to update the database via the Package Manager Console with an 'update-database' I receive this error:

我有连接字符串,可以使用Package Manager控制台轻松添加迁移。如果我运行我的应用程序,那么Database.Migrate()将很容易地迁移迁移。但是,如果我尝试通过Package Manager控制台使用‘UPDATE-DATABASE’来更新数据库,我会收到这个错误:


System.ArgumentException: Host can't be null
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnection.Open()
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 contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, 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

I do not know what is happening, if I am missing a nuget package, etc. Any possible help and explanation for what is happening would be greatly appreciated.

我不知道发生了什么,如果我丢失了一个Nuget包,等等。任何可能的帮助和解释正在发生的事情将非常感激。


更多回答
优秀答案推荐

You should set ConnectionStrings in program.cs|startup.cs.

您应该在Program.cs|Startup.cs中设置ConnectionStrings。


Add this into the program.cs (.net7)

将此代码添加到Program.cs(.net7)中


builder.Services.Configure<ConnectionStrings>(
builder.Configuration.GetSection(nameof(ConnectionStrings))
);

or startup.cs (.net6):

或者Startup.cs(.net6):


services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));


add bellow lines in Program.cs file

在Program.cs文件中添加以下行


builder.Services.AddDbContext<ApplicationDBContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IDataAccessProvider, DataAccessProvider>();

and bellow connection string in appsettings.json

和下面appsettings.json中的连接字符串


  "ConnectionStrings": {
    "DefaultConnection": "User ID=postgres;Password=******;Host=127.0.0.1;Port=****;Database=at;"
  },   "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"


I Solved it. It had to do with the way I was building the connection string on runtime and not buildtime.

我解决了这个问题。这与我在运行时而不是构建时构建连接字符串的方式有关。



You should export your env variables first from terminal like this:

您应该首先从终端导出您的环境变量,如下所示:


export $(grep -v '^#' ./dev.env | xargs)


{dev.env} -> change it to your env file




Check your connection string in your startup class you may have different connection string name with the config of the database in the startup when you are using appsetting.json

检查启动类中的连接字符串当您使用appsetting.json时,启动时数据库的配置可能具有不同的连接字符串名称


Startup configuration

启动配置


appsetting.json

Appsetting.json



Ok this may sounds stupid. But our team accidentally ignore the relevant appsettings.json file for our contract test.

好吧,这可能听起来很愚蠢。但是我们的团队意外地忽略了合同测试的相关appsettings.json文件。


CopyToPublishDirectory was set to Never.

CopyToPublishDirectory设置为Never。


Thus the connection string was never set in the first place. When docker runs, the connection string was empty.

因此,从一开始就没有设置连接字符串。当docker运行时,连接字符串为空。


appsetting.json was ignored from being published



I have this code snippet that read env file and set it to process environment variables

我有这个代码片段,它读取环境文件并将其设置为处理环境变量


      using System.Runtime.CompilerServices;

namespace Bug_tracker.Utils
{
public static class Env
{
[ModuleInitializer]
public static void ReadEnvFile()
{
if (!File.Exists("./.env")) return;

foreach (var line in File.ReadAllLines("./.env"))
{
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#")) continue;

var parts = line.Split('=', 2);

if (parts.Length == 2)
{
var name = parts[0].Trim();
var value = parts[1].Trim();
value = value.Substring(1, value.Length - 2);
Console.WriteLine(name + "=" + value);
Environment.SetEnvironmentVariable(name, value);
};
};

}

}
}

Using attribute [ModuleInitializer] to mark a method that will run when a module is loaded

使用属性[ModuleInitializer]标记将在加载模块时运行的方法


This solution fixes my problem

这个解决方案解决了我的问题



I solved this problem by putting the --startup-project flag in my migration script like this:

我通过在迁移脚本中放置--startup-project标志解决了这个问题,如下所示:


dotnet ef database update --startup-project "startup project path" --project "DbContext path" --verbose

DotNet ef数据库更新--启动-项目“启动项目路径”--项目“DbContext路径”--详细


更多回答

How did you solve it? Did you find a solution on runtime? I am using enviroment variables and have to set them in the powershell to make it work. Somehow it does not tale the default values...

你是怎么解决的?你在运行时找到解决方案了吗?我正在使用环境变量,并且必须在PowerShell中设置它们才能使其工作。不知何故,它并不符合缺省值。

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

正如它目前所写的,你的答案并不清楚。请编辑以添加更多详细信息,以帮助其他人了解这是如何解决提出的问题的。你可以在帮助中心找到更多关于如何写出好答案的信息。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com