1
votes

How to resolve my "HelloEFCore" .NET Core console app exception? I use Npgsql Entity Framework Core Provider (https://www.npgsql.org/efcore/)

Unable to create an object of type 'AppContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

It occurs when I try to do initial migration

dotnet ef migrations add CreateDatabase

Code that I'm working with:

Program.cs

class Program
{
    static void Main(string[] args)
    {
        AppContext a = new AppContext("Server=127.0.0.1; port=5432; user_id=postgres; password=root; database=db; pooling=true");
    }
}

Product.cs

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public int Quantity { get; set; }
    public int BrandId { get; set; }
    public Brand Brand { get; set; }
}

Brand.cs

public class Brand
{
    public int BrandId { get; set; }
    public string Name { get; set; }
    public List<Product> Products { get; set; } = new List<Product>();
}

AppContext.cs

public class AppContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Brand> Brands { get; set; }
    private readonly string _connectionString;
    public AppContext(string connectionString)
    {
        _connectionString = connectionString ?? 
            throw new ArgumentException("connectionString is empty.");
    }
    protected override void OnConfiguring(DbContextOptionsBuilder builder)
    {
        builder.UseNpgsql(_connectionString);
    }
}

efstart.csproj

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
  <OutputType>Exe</OutputType>
  <TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.8" />
  <PackageReference Include="Npgsql" Version="4.1.3"/>
  <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.3"/>
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.4"/>
</ItemGroup>
</Project>

Application compiles well. I use pgAdmin on Ubuntu 20.04.

1
Please check my answer to the following question: stackoverflow.com/questions/64493635/… The solution should also work in your context, just adapt context name, database and path/filename to your needs.Thomas Erdösi

1 Answers

2
votes

You need to implement IDesignTimeDbContextFactory interface to make your solution work without any problems.

public class AppContext Factory : IDesignTimeDbContextFactory< AppContext>
{
    public AppContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<AppContext>();

        builder.UseNpgsql(connectionString);

        return new DataContext(builder.Options);
    }
}