Running dotnet ef migrations add InitialCreate with Postgres on Mac, I get a build failure

22 Views Asked by At

I'm trying to add a migration to my .NET Core application using Entity Framework Core, but I'm encountering issues with the dotnet ef migrations add command.

Here's what I've tried and the error I get:

Steps taken

  • Installed Entity Framework Core tools globally using dotnet tool install --global dotnet-ef.
  • Created a DbContext class (YourDbContext) inheriting from DbContext.
  • Defined my table Post with the necessary columns
  • Configured the OnConfiguring method in YourDbContext to use Npgsql for PostgreSQL.

Problem encountered

When I run the command dotnet ef migrations add InitialCreate from the root directory of my project, the command fails to execute.

However, it doesn't provide clear error messages, making it difficult for me to identify the root cause of the issue.

Error message

The error message I'm seeing is:

Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[ApplicationDbContext]' while attempting to activate 'ApplicationDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Troubleshooting Attempts

  • Ensured that the Entity Framework Core packages are correctly installed in my project file (csproj).
  • Verified that my DbContext class and entity are correctly configured.
  • Checked for any potential misspellings or incorrect options in the command.

Additional Context

  • Project is using .NET Core 8.
  • Using Entity Framework Core version 8.0.3
  • PostgreSQL database
  • Operating system: Mac OS.

Can anyone provide guidance on how to troubleshoot and resolve this issue? Any insights or suggestions would be greatly appreciated. Thank you!

ApplicationDbContext.cs:

using Microsoft.EntityFrameworkCore;
using Nlighten.Models;

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

    public DbSet<Article> Articles { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Server=127.0.0.1;Port=5432;Database=mydb;User Id=postgres;Password=mypwd;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}
0

There are 0 best solutions below