Không thể tạo đối tượng kiểu 'AppContext'. Npgsql + EFCore

Oct 23 2020

Cách giải quyết ngoại lệ ứng dụng bảng điều khiển .NET Core "HelloEFCore" của tôi? Tôi sử dụng Npgsql Entity Framework Core Provider (https://www.npgsql.org/efcore/)

Không thể tạo đối tượng kiểu 'AppContext'. Để biết các mẫu khác nhau được hỗ trợ tại thời điểm thiết kế, hãy xemhttps://go.microsoft.com/fwlink/?linkid=851728

Nó xảy ra khi tôi cố gắng di chuyển ban đầu

dotnet ef migrations add CreateDatabase

Mã mà tôi đang làm việc với:

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>

Ứng dụng biên dịch tốt. Tôi sử dụng pgAdmin trên Ubuntu 20.04.

Trả lời

2 AVTUNEY Oct 23 2020 at 19:30

Bạn cần triển khai giao diện IDesignTimeDbContextFactory để giải pháp của bạn hoạt động mà không gặp bất kỳ sự cố nào.

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

        builder.UseNpgsql(connectionString);

        return new DataContext(builder.Options);
    }
}