Receiving weird host can't be null error with ef core
Asked Answered
R

9

11

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

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:

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.

Reclusion answered 30/7, 2020 at 1:17 Comment(0)
A
4

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

Add this into the program.cs (.net7)

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

or startup.cs (.net6):

services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
Angkor answered 16/12, 2022 at 17:51 Comment(0)
M
1

add bellow lines in Program.cs file

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

and bellow connection string in appsettings.json

  "ConnectionStrings": {
    "DefaultConnection": "User ID=postgres;Password=******;Host=127.0.0.1;Port=****;Database=at;"
  },   "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
Miscreant answered 16/2, 2023 at 9:10 Comment(0)
P
1

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

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

Paralytic answered 11/9, 2023 at 2:43 Comment(1)
Thanks - that solved my problem as the migration files were placed in another project than the executable and was unable to use appsettings.json from the executable project.Disestablish
P
1

You should set ConnectionStrings in Program.cs

PotgreSQL(NpgSQL) was used here

Add this into the Program.cs (.net8)

builder.Services.AddDbContext<AppDataContext>(options =>
{
    options.UseNpgsql(builder.Configuration.GetConnectionString("YourConnectionName"));
});

Add this into the appsettings.json

 "ConnectionStrings": {
  "YourConnectionName": "Host=your_host; Port=your_port; User Id=postgres; Password=your_password; Database=your_database_name"
}

Add this into the your DbContext

    public class AppDataContext : DbContext
    {
        public AppDataContext(DbContextOptions<AppDataContext> options): base(options)
        { }

        ///
    }

Then in the Package Manager Console:

  1. add-migration Initial
  2. update-database
Portfolio answered 4/1 at 18:22 Comment(0)
R
0

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

Reclusion answered 30/7, 2020 at 2:49 Comment(1)
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...Esma
F
0

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

Flipper answered 2/11, 2021 at 10:13 Comment(0)
S
0

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

Startup configuration

appsetting.json

Safar answered 16/11, 2022 at 13:55 Comment(0)
R
0

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

CopyToPublishDirectory was set to Never.

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

appsetting.json was ignored from being published

Rabassa answered 9/3, 2023 at 3:24 Comment(0)
P
0

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

This solution fixes my problem

Participial answered 24/3, 2023 at 1:2 Comment(1)
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.Refract

© 2022 - 2024 — McMap. All rights reserved.