Я пытаюсь создать свою базу данных с помощью .NET Core 2.2 и Angular и столкнулся с этой ошибкой:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
У меня есть конструктор по умолчанию в моем классе ApplicationDbContext
.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base()
{
}
}
Моя программа cs выглядит нормально для меня:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(SetUpConfiguration)
.UseStartup<Startup>();
private static void SetUpConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
{
builder.Sources.Clear();
builder.AddJsonFile("appsettings.json", false, true)
.AddEnvironmentVariables();
}
}
И мой запуск регистрирует БД:
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<ApplicationDbContext>(cfg => {
cfg.UseSqlServer(_config.GetConnectionString("LevanaConnectionString"));
});
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
Вы не передаете параметры в базовый конструктор:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts) // <-- this
{
}
}
Как мы видим в первом сообщении: «Если используется AddDbContext, также убедитесь, что ваш тип DbContext принимает объект DbContextOptions в своем конструкторе и передает его базовому конструктору для DbContext».
Вы используете «AddDbContext» в классе «ConfigureServices», но не передаете «DbContextOptions» для базового конструктора «DbContext» в «ApplicationDbContext».
Вы можете попробовать это:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts)
{
}
}