带有实体框架 7 的 ASP.NET 5 - 尝试设定数据库种子时未配置任何数据库提供程序



我正在使用EF7玩 ASP.NET 5项目。我已经创建了基本的测试模型,进行了代码优先迁移,数据库更新,现在我尝试将一些数据发送到创建的数据库。

我正在使用项目tepmplate中包含的默认DbContext(ApplicationDbContext.cs)。当我尝试使用控制器发送数据时,一切正常。现在我想在启动时播种数据库。为此,我创建了 ApplicationDbContext 的种子扩展方法:

public static class ProjectExtensions
{
    public static void SeedDB(this ApplicationDbContext context)
    {
        context.Add(new TestingModel() { Name = "foo" });
        context.SaveChanges();
    }
}

然后,我在 Startup 中添加了方法调用.cs配置方法中:

if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            using (var context = new ApplicationDbContext())
            {
                context.SeedDB();
            }
        }

但是当我尝试运行该项目时,系统会抛出异常

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.Core.dll but was not handled in user code
Additional information: No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.

这似乎很奇怪,因为数据库提供程序应该已经配置好了。正如我所说,我正在使用默认设置的默认上下文。当我调用控制器进行一些 CRUD 操作时,一切正常。

谁知道,哪里有错误?

找到解决方案。在 Startup .cs 配置方法中的此编辑似乎已修复所有问题:

if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                           .CreateScope())
            {
                serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
                serviceScope.ServiceProvider.GetService<ApplicationDbContext>().SeedDB();
            }
        }

希望这可以帮助有相同问题的人:)

最新更新