更新数据库EF Core 5失败代码优先

问题描述

我将环境升级到 ASP.NET Core 5.01,但在使用代码优先方法更新数据库时遇到了一些困难。 Add-Migration 命令按预期工作并生成正确的迁移源文件。但是,当我尝试运行 Update-Database 时出现错误。这是我的 PMC 的输出:

PM> add-migration Project
Build started...
Build succeeded.
To undo this action,use Remove-Migration.
PM> Update-Database
Build started...
Build succeeded.
Unable to create an object of type 'SaberDbContext'. For the different patterns supported at design time,see https://go.microsoft.com/fwlink/?linkid=851728
PM> 

运行 Update-Database -verbose 时,我得到以下输出:

> C:\Program Files\dotnet\dotnet.exe exec --depsfile
> C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data\bin\Debug\net5.0\SaberTooth.Model.deps.json
> --additionalprobingpath C:\Users\valere\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig
> C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data\bin\Debug\net5.0\SaberTooth.Model.runtimeconfig.json
> C:\Users\valere\.nuget\packages\microsoft.entityframeworkcore.tools\5.0.1\tools\netcoreapp2.0\any\ef.dll
> database update --verbose --no-color --prefix-output --assembly
> C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data\bin\Debug\net5.0\SaberTooth.Model.dll
> --startup-assembly C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data\bin\Debug\net5.0\SaberTooth.Model.dll
> --project-dir C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data\ --language C# --working-dir C:\TFS_VSTUDIO\SaberToothPortal --root-namespace SaberTooth.Model Using assembly 'SaberTooth.Model'. Using startup assembly 'SaberTooth.Model'. Using application base
> 'C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data\bin\Debug\net5.0'.
> Using working directory
> 'C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data'. Using root
> namespace 'SaberTooth.Model'. Using project directory
> 'C:\TFS_VSTUDIO\SaberToothPortal\SaberTooth.Data\'. Remaining
> arguments: . Finding DbContext classes... Finding
> IDesignTimeDbContextFactory implementations... Finding application
> service provider in assembly 'SaberTooth.Model'... Finding
> Microsoft.Extensions.Hosting service provider... No static method
> 'CreateHostBuilder(string[])' was found on class 'Program'. No
> application service provider was found. Finding DbContext classes in
> the project... Found DbContext 'SaberDbContext'.
> Microsoft.EntityFrameworkCore.Design.OperationException: Unable to
> create an object of type 'SaberDbContext'. For the different patterns
> supported at design time,see
> https://go.microsoft.com/fwlink/?linkid=851728  --->
> System.InvalidOperationException: Unable to resolve service for type
> 'Microsoft.EntityFrameworkCore.DbContextOptions`1[SaberTooth.Model.SaberDbContext]'
> while attempting to activate 'SaberTooth.Model.SaberDbContext'.    at
> Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider
> provider)    at
> Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider
> provider,Type instanceType,Object[] parameters)    at
> Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider
> provider,Type type)    at
> Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
> --- End of inner exception stack trace ---    at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
> at
> Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1
> factory)    at
> Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String
> contextType)    at
> Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String
> targetMigration,String connectionString,String contextType)    at
> Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String
> targetMigration,String contextType)    at
> Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
> at
> Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action
> action)

输出表明 Program.cs 类中没有 CreateHostBuilder,但它显然存在:

namespace SaberTooth.Model
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

如果我随后尝试发出 Remove-Migration 命令,我会得到相同的结果:

PM> Remove-Migration
Build started...
Build succeeded.
Unable to create an object of type 'SaberDbContext'. For the different patterns supported at design time,see https://go.microsoft.com/fwlink/?linkid=851728
PM>

我在错误消息中查找了建议的链接,但我没有看到我哪里做错了。我还使用完全相同的步骤(在升级之前)毫无问题地执行了六次迁移:

1.  Create the Model:  
2.  Create the Interface:
3.  Add a DBSet Declaration in the SaberDbContext.cs File
4.  Create the Repository
5.  Add a Scope to the Startup.cs File
6.  Run the add-migration command
7.  Run the update-database command

我对 EF 还很陌生。这是我第一次尝试将它用于项目。任何帮助将不胜感激。升级到 .Net Core 5.0.1 后,我是否做错了什么?

谢谢

--- 瓦尔

解决方法

我终于让它起作用了。这是我所做的:

我更新了 Startup 类中的 Configure Services 方法并更改了以下条目:

services.AddDbContext<SaberDbContext>();

到:

    string _connectionString;
    string appSettings = String.Concat(Directory.GetCurrentDirectory(),"/appsettings.json");
    var configurationSettings = new ConfigurationBuilder().AddJsonFile(appSettings).Build();
    _connectionString = configurationSettings["ConnectionStrings:DefaultConnection"];

    services.AddDbContext<SaberDbContext>(options =>
        options.UseSqlServer(_connectionString));

这就成功了。不知道为什么这适用于 .NET Core 3.x 而它不适用于 5.x。就像我说的,我是实体框架和 Web 应用程序开发的新手(这是我的第一个项目),所以我确定我没有使用正确的定义。不过现在它可以工作!

--- 瓦尔

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...