【问题标题】:Entity Framework 7 no database provider is configured => when migrations are moved to another projectEntity Framework 7 未配置数据库提供程序 => 迁移到另一个项目时
【发布时间】:2015-11-22 21:13:31
【问题描述】:

我是 EF7 的新手。我知道这是一个重复的问题:

No database providers are configured EF7

但是,在你想结束这个问题之前等一下……然后继续阅读

 services.AddEntityFramework()
         .AddSqlServer()
         .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

 services.AddIdentity<ApplicationUser, IdentityRole>()
         .AddEntityFrameworkStores<ApplicationDbContext>()
         .AddDefaultTokenProviders();

  services.AddScoped<TestRepository, TestRepository>();

现在我在我的 EF 项目的 cmd 窗口上运行 dnx ef 数据库更新命令并得到这个错误:

C:\TGB.DataAccess>dnx ef database update
System.InvalidOperationException: 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.
   bei Microsoft.Data.Entity.Internal.DatabaseProviderSelector.SelectServices(ServiceProviderSource providerSource)
   bei Microsoft.Data.Entity.Internal.DbContextServices.<>c__DisplayClass6_0.<Initialize>b__0()
   bei Microsoft.Data.Entity.Internal.LazyRef`1.get_Value()
   bei Microsoft.Data.Entity.Internal.DbContextServices.get_DatabaseProviderServices()
   bei Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_8(IServiceProvider p)
   bei Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
   bei Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   bei Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
   bei Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   bei Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   bei Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   bei Microsoft.Data.Entity.Design.Internal.DesignTimeServicesBuilder.Build(DbContext context)
   bei Microsoft.Data.Entity.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   bei Microsoft.Data.Entity.Commands.Program.Executor.<>c__DisplayClass7_0.<UpdateDatabase>b__0()
   bei Microsoft.Data.Entity.Commands.Program.Executor.Execute(Action action)
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.

现在我尝试根据我粘贴在顶部的解决方案链接更改我的ApplicationDbContext 的构造函数:

这是我的代码:

我的 ApplicationDbContext.cs 实际上是空的,这意味着我没有覆盖任何内容。

查看基类的基类,有带参数 DbContextOptions 的重载构造函数,但我的构造函数不能传递任何东西?!

  //
        // Summary:
        //     Initializes a new instance of Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext.
        //
        // Parameters:
        //   options:
        //     The options to be used by a Microsoft.Data.Entity.DbContext.
        public IdentityDbContext(DbContextOptions options);

我这边出了什么问题?我正在使用 EF 7 RC1 和 dnx 451。

仅当您将 ApplicationDbContext/ApplicationUser 和整个 Migrations 文件夹移动到一个额外的“DataAccess”项目时才会发生这种情况。然后一切似乎都坏了。

【问题讨论】:

  • 您是否尝试指定上下文,例如dnx database update -c ApplicationDbContext
  • 您也可以指定项目-p &lt;project&gt;
  • 我通过 CMD 直接进入 DataAccess 项目并运行 dnx ef database update -c ApplicationDbContext => 与以前相同的错误!
  • 我对 -p TGB.DataAccess 做了同样的事情 => 和以前一样的错误!
  • 我更新了我的问题并删除了我的 ApplicationDbContext 代码,因为我没有使用重载的构造函数,因为没有什么可以重载......我想这就是问题所在。

标签: c# asp.net-core entity-framework-core


【解决方案1】:
  1. 使用 Web 应用程序模板(身份验证:个人用户帐户)创建一个名为“WebProject”的新 ASP.NET Web 应用程序。

  2. 现在将另一个项目添加到名为“DataAccess”的解决方案中(假设是类库类型,尽管它不相关)

  3. 现在将 ApplicationDbContext/ApplicationUser 文件和迁移文件夹移至 DataAccess 项目。

  4. 在此阶段构建将失败,因此我们需要更正 project.json 以获得正确的引用。

  5. 对于DataAccess项目,添加以下依赖项

    "dependencies": {
        "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
        "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"
    }
    
  6. 对于 WebProject,添加 DataAccess 作为依赖项。由于DataAccess 引用了以上 2 个包,您可以从 WebProject 中删除这些引用。
    构建现在应该成功,您可以启动 Web 应用程序。

如何使用 ef 迁移:

在命令行中,转到 WebProject 的目录(而不是 DataAccess 项目)。 所有的 ef 命令都可以从这里正常工作。

要向 DataAccess 项目的 Migrations 文件夹添加新的迁移,您需要使用 -p 标志。喜欢,
dnx ef migrations add Sample -p DataAccess

出现问题是因为命令是从 DataAccess 项目中的 cmd 运行的。正在初始化所有服务的启动类在 WebProject 中。当您尝试从 DataAccess 目录运行命令时,dnx ef 将被识别,因为 EntityFramework.Commands 被引用,但是当您尝试使用迁移时,服务未初始化,因此它将失败抛出上述异常。

【讨论】:

    【解决方案2】:

    尝试将 Context 类移动到“DataAccess”项目中,并在“DataAccess”项目中覆盖 Context 的 OnConfiguring 方法,然后运行迁移。

    public partial class MyContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(@"Server=****;Database=***;user id=***;password=***");
        }
    }
    

    如果您不想对连接字符串进行硬编码,也可以执行以下操作。 DI 将为您注入选项;

    public partial class MyContext : DbContext
    {
        public MyContext(DbContextOptions<MyContext> options) : base(options)
        {
    
        }
    }
    

    在您的 Startup.cs 上;

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddSqlServer()            
            .AddDbContext<WtContext>(options =>
                options.UseSqlServer(Configuration["Data:MyDb:ConnectionString"]));
    }
    

    还有你的 appsetting.json;

    {
      "Data": {
        "MyDb": {
          "ConnectionString": "**********"
        }
      }
    }
    

    【讨论】:

    • THIS public MyContext(DbContextOptions options) : base(options) 在我的代码中是不可能的,因为 MyContext 没有带有任何参数的构造函数。是的,我继承自 DbContext!
    • 如何在 Controller 或任何需要的地方实例化 MyContext()?
    猜你喜欢
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2011-01-12
    • 2015-11-01
    • 1970-01-01
    • 2022-12-09
    • 2021-03-18
    • 2016-03-31
    相关资源
    最近更新 更多