Я пытаюсь создать сценарии/экспортировать миграцию кода Entity Framework Core сначала в конвейер Azure DevOps CI, но возникает ошибка. Приведенная ниже команда отлично работает в моей Visual Studio локально и создает файл sql, и несколько месяцев назад работа команды также отлично работала в DevOps (не уверен, что это связано с обновлением).
dotnet ef migrations script --project Booking.Core
--startup-project Booking.Management --idempotent
--output $(build.artifactstagingdirectory)/migrate.sql --verbose
В моем проекте используется версия .NET Core 3.1.5, а также в конвейере. Я уверен, что команда dotnet-ef
доступна, например
dotnet tool install --global dotnet-ef --version 3.1.5
Но я все еще получаю эту ошибку:
2020-12-13T09:13:27.8973893Z ##[section]Starting: EF Core Migrations SQL Export
2020-12-13T09:13:27.9112206Z ==============================================================================
2020-12-13T09:13:27.9112480Z Task : PowerShell
2020-12-13T09:13:27.9112737Z Description : Run a PowerShell script on Linux, macOS, or Windows
2020-12-13T09:13:27.9112956Z Version : 2.179.1
2020-12-13T09:13:27.9113144Z Author : Microsoft Corporation
2020-12-13T09:13:27.9113446Z Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
2020-12-13T09:13:27.9113759Z ==============================================================================
2020-12-13T09:13:28.8144250Z Generating script.
2020-12-13T09:13:28.8694723Z ========================== Starting Command Output ===========================
2020-12-13T09:13:28.8987598Z ##[command]"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\fa82967e-1e57-4dba-932d-1453e98ef510.ps1'"
2020-12-13T09:13:29.4639310Z Using project 'Booking.Core\Booking.Core.csproj'.
2020-12-13T09:13:29.4640261Z Using startup project 'Booking.Management\Booking.Management.csproj'.
2020-12-13T09:13:29.4661731Z Writing 'Booking.Core\obj\Booking.Core.csproj.EntityFrameworkCore.targets'...
2020-12-13T09:13:29.4713085Z dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\VssAdministrator\AppData\Local\Temp\tmpBC2B.tmp /verbosity:quiet /nologo Booking.Core\Booking.Core.csproj
2020-12-13T09:13:30.5894726Z Writing 'Booking.Management\obj\Booking.Management.csproj.EntityFrameworkCore.targets'...
2020-12-13T09:13:30.5904170Z dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\VssAdministrator\AppData\Local\Temp\tmpC091.tmp /verbosity:quiet /nologo Booking.Management\Booking.Management.csproj
2020-12-13T09:13:31.4844212Z Build started...
2020-12-13T09:13:31.4848105Z dotnet build Booking.Management\Booking.Management.csproj /verbosity:quiet /nologo
2020-12-13T09:13:39.4566730Z
2020-12-13T09:13:39.4680169Z Build succeeded.
2020-12-13T09:13:39.4681347Z 0 Warning(s)
2020-12-13T09:13:39.4681964Z 0 Error(s)
2020-12-13T09:13:39.4682460Z
2020-12-13T09:13:39.4683029Z Time Elapsed 00:00:07.53
2020-12-13T09:13:39.5195940Z Build succeeded.
2020-12-13T09:13:39.5465861Z dotnet exec --depsfile D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Management.deps.json --additionalprobingpath C:\Users\VssAdministrator\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Management.runtimeconfig.json C:\Users\VssAdministrator\.dotnet\tools\.store\dotnet-ef\3.1.5\dotnet-ef\3.1.5\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll migrations script --idempotent --output D:\a\1\a/migrate.sql --assembly D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Core.dll --startup-assembly D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Management.dll --project-dir D:\a\1\s\Booking.Core\ --language C# --working-dir D:\a\1\s --verbose --root-namespace Booking.Core
2020-12-13T09:13:39.7619178Z Using assembly 'Booking.Core'.
2020-12-13T09:13:39.7621486Z Using startup assembly 'Booking.Management'.
2020-12-13T09:13:39.7623162Z Using application base 'D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1'.
2020-12-13T09:13:39.7624489Z Using working directory 'D:\a\1\s\Booking.Management'.
2020-12-13T09:13:39.7627735Z Using root namespace 'Booking.Core'.
2020-12-13T09:13:39.7628656Z Using project directory 'D:\a\1\s\Booking.Core\'.
2020-12-13T09:13:40.0447318Z Finding DbContext classes...
2020-12-13T09:13:40.0448237Z Finding IDesignTimeDbContextFactory implementations...
2020-12-13T09:13:40.1345335Z Finding application service provider...
2020-12-13T09:13:40.1352141Z Finding Microsoft.Extensions.Hosting service provider...
2020-12-13T09:13:40.1387349Z Using environment 'Development'.
2020-12-13T09:13:41.3123215Z Rollbar.RollbarException: Failed to configure using invalid configuration prototype!
2020-12-13T09:13:41.3123976Z at Rollbar.RollbarLogger.ValidateConfiguration(IRollbarConfig rollbarConfig)
2020-12-13T09:13:41.3124504Z at Rollbar.RollbarLogger.Configure(IRollbarConfig settings)
2020-12-13T09:13:41.3125776Z at Rollbar.RollbarLogger.Rollbar.IRollbar.Configure(IRollbarConfig settings)
2020-12-13T09:13:41.3127983Z at Booking.Management.Startup.ConfigureServices(IServiceCollection services) in D:\a\1\s\Booking.Management\Startup.cs:line 136
2020-12-13T09:13:41.3128521Z at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
2020-12-13T09:13:41.3129014Z at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
2020-12-13T09:13:41.3129472Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
2020-12-13T09:13:41.3129921Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
2020-12-13T09:13:41.3130590Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
2020-12-13T09:13:41.3131087Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
2020-12-13T09:13:41.3131685Z at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
2020-12-13T09:13:41.3132193Z at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
2020-12-13T09:13:41.3132570Z at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
2020-12-13T09:13:41.3132842Z at Microsoft.Extensions.Hosting.HostBuilder.Build()
2020-12-13T09:13:41.3133338Z An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Failed to configure using invalid configuration prototype!
2020-12-13T09:13:41.3133808Z No application service provider was found.
2020-12-13T09:13:41.3309579Z Finding DbContext classes in the project...
2020-12-13T09:13:41.3402462Z Found DbContext 'ApplicationDbContext'.
2020-12-13T09:13:41.3673060Z Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
2020-12-13T09:13:41.3674225Z ---> System.MissingMethodException: No parameterless constructor defined for type 'Booking.Core.Data.ApplicationDbContext'.
2020-12-13T09:13:41.3674932Z at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
2020-12-13T09:13:41.3675640Z at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
2020-12-13T09:13:41.3676267Z at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
2020-12-13T09:13:41.3676691Z at System.Activator.CreateInstance(Type type)
2020-12-13T09:13:41.3677358Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
2020-12-13T09:13:41.3677798Z --- End of inner exception stack trace ---
2020-12-13T09:13:41.3678247Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
2020-12-13T09:13:41.3678609Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
2020-12-13T09:13:41.3678993Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
2020-12-13T09:13:41.3681847Z at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.ScriptMigration(String fromMigration, String toMigration, Boolean idempotent, String contextType)
2020-12-13T09:13:41.3682773Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigrationImpl(String fromMigration, String toMigration, Boolean idempotent, String contextType)
2020-12-13T09:13:41.3683262Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigration.<>c__DisplayClass0_0.<.ctor>b__0()
2020-12-13T09:13:41.3683647Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
2020-12-13T09:13:41.3684014Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
2020-12-13T09:13:41.3684531Z Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
2020-12-13T09:13:41.6277035Z ##[error]PowerShell exited with code '1'.
2020-12-13T09:13:41.6727543Z ##[section]Finishing: EF Core Migrations SQL Export
Мой файл Program.cs
выглядит так:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Мой ApplicationDbContext
имеет такие конструкторы, как:
protected ApplicationDbContext() {}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor contextAccessor) : base(options)
{
_contextAccessor = contextAccessor;
}
Мой файл Startup.cs
выглядит так:
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)standard environment name (e.g: Local).
.AddUserSecrets<Startup>()
.AddEnvironmentVariables();
Configuration = builder.Build();
Environment = env;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<User, Role>(
config => {...})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddUserValidator<IdendityUserValidator<User>>();
}
@IvanStoev, большое спасибо за направление. Я думал, что Rollbar не работает из-за проблемы с контекстом БД. Я мог бы исправить проблему сейчас, это был просто пустой токен доступа, который Rollbar отказывался принимать
Конфигурация полосы прокрутки не удалась, потому что для токена доступа ожидалась строка, которая не была нулевой/пустой. Поскольку я храню токен доступа Rollbar в конфигурации Azure AppService, а в файле appsettings.json не указан токен доступа, возникает ошибка. Поэтому я добавил токен доступа в appsettings.json с фиктивным непустым строковым значением. Это помогает Rollbar настроить себя и не дать сбой.
Есть
Rollbar.RollbarException
во времяConfigureServices
, которое вам нужно исследовать. С этим (или любым другим) исключением EF Core не может использовать службы приложений для получения экземпляраDbContext
и пытается использовать другие способы (фабрика времени разработки, конструктор без параметров), которые не применимы в вашем случае, отсюда и второе исключение.