.net-core - “错误无法创建 'AppDbContext' 类型的对象。对于设计时支持的不同模式”
问题描述
我正在使用 VS 2019 预览版和 .NET Core 3.0 创建一个 ASP .NET Core Web API。当我尝试执行:add-migration 时,我收到错误消息: “无法创建 'AppDbContext' 类型的对象。对于设计时支持的不同模式,...”
下面是我的上下文文件:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{ }
public DbSet<Categoria> Categorias { get; set; }
public DbSet<Produto> Produtos { get; set; }
}
我的 ConfigureServices 方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers().AddNewtonsoftJson();
}
我的 appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;DataBase....."
},
...
}
我总是使用这种方法并且它有效。
我还尝试在上下文类中创建一个空构造函数,但出现此错误: “System.InvalidOperationException: No database provider has been configured for this DbContext ...”
我忘记了一些细节吗?
注意:这在 ASP .NET Core 2.2 中运行良好
解决方案
DbContext
您可以通过实现接口告诉迁移如何创建您的IDesignTimeDbContextFactory<TContext>
:如果在与派生的相同项目中DbContext
或在应用程序的启动项目中找到实现此接口的类,则工具会绕过其他创建DbContext
和使用设计的方法- 时间工厂代替。
有关更多信息,请参阅此链接
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace MyProject
{
public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseMySql("Server=localhost;DataBase.....");
return new AppDbContext(optionsBuilder.Options);
}
}
}