Impossible de créer un objet de type 'AppContext'. Npgsql + EFCore

Oct 23 2020

Comment résoudre mon exception d'application de console .NET Core «HelloEFCore»? J'utilise Npgsql Entity Framework Core Provider (https://www.npgsql.org/efcore/)

Impossible de créer un objet de type 'AppContext'. Pour les différents modèles pris en charge au moment de la conception, voirhttps://go.microsoft.com/fwlink/?linkid=851728

Cela se produit lorsque j'essaye de faire la migration initiale

dotnet ef migrations add CreateDatabase

Code avec lequel je travaille:

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");
    }
}

Produit.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; }
}

Marque.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>

L'application se compile bien. J'utilise pgAdmin sur Ubuntu 20.04.

Réponses

2 AVTUNEY Oct 23 2020 at 19:30

Vous devez implémenter l'interface IDesignTimeDbContextFactory pour que votre solution fonctionne sans aucun problème.

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

        builder.UseNpgsql(connectionString);

        return new DataContext(builder.Options);
    }
}