无法创建“ AppContext”类型的对象。 Npgsql + EFCore

时间:2020-10-23 12:23:36

标签: postgresql .net-core entity-framework-core

如何解决我的“ HelloEFCore” .NET Core控制台应用程序异常?我使用Npgsql实体框架核心提供程序(https://www.npgsql.org/efcore/

无法创建类型为“ AppContext”的对象。有关设计时支持的不同模式,请参见https://go.microsoft.com/fwlink/?linkid=851728

当我尝试进行初始迁移时会发生

dotnet ef migrations add CreateDatabase

我正在使用的代码:

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>

应用程序编译良好。我在Ubuntu 20.04上使用pgAdmin。

1 个答案:

答案 0 :(得分:2)

您需要实现IDesignTimeDbContextFactory接口,以使您的解决方案正常工作。

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

        builder.UseNpgsql(connectionString);

        return new DataContext(builder.Options);
    }
}