【问题标题】:ASP.NET 5 with Entity Framework 7 - No database providers are configured when try to seed DB带有 Entity Framework 7 的 ASP.NET 5 - 尝试播种 DB 时未配置数据库提供程序
【发布时间】:2016-02-29 14:28:34
【问题描述】:

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

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

public static class ProjectExtensions
{

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

}

然后,我在 Configure 方法中的 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 操作时,一切正常。

有谁知道,哪里出错了?

【问题讨论】:

  • 我没用过EF7,只知道一点。但是您没有显示错误方法提到的代码。而且您的配置没有显示注册任何提供程序。我知道 EF7 支持许多提供程序,并且我假设您需要按照错误中的说明告诉它要使用哪个提供程序。总是尝试错误告诉你做什么。

标签: asp.net asp.net-mvc entity-framework web-applications


【解决方案1】:

找到解决方案。在 Configure 方法中的 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();
            }

        }

希望这可以帮助遇到同样问题的人:)

【讨论】:

    猜你喜欢
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2016-03-31
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多