question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Migrations script not using IDesignTimeDbContextFactory

See original GitHub issue

File a bug

If a class implementing this interface is found in either the same project as the derived DbContext or in the application’s startup project, the tools bypass the other ways of creating the DbContext and use the design-time factory instead.

I have a problem with migrations script command failing. It seems it doesn’t use the design time factory I have implemented and tries to run the host builder instead (which doesn’t have any connection string on the build server).

If I set a (fake) connection string, everything works fine. That makes me thinking the factory is not actually used even though, as the log suggests, it has been noticed by the tools.

Is this a bug or am I doing something wrong?

My factory

It uses the parameterless constructor with no connections string supplied. As it is only used to generate the migrations script, it should all be fine as no db connection is ever needed.

namespace MyApp
{
    public class MyAppDbContextFactory : IDesignTimeDbContextFactory<MyAppDbContext>
    {
        public MyAppDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<MyAppDbContext>();
            optionsBuilder.UseSqlServer();

            return new MyAppDbContext(optionsBuilder.Options);
        }
    }
}

Verbose output

Local paths and project names changed/removed.

dotnet ef migrations script --idempotent --context MyAppDbContext -o migrations.sql --no-build --verbose
Using project '###.csproj'.
Using startup project '###.csproj'.
Writing '###.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=###\AppData\Local\Temp\tmp42B.tmp /verbosity:quiet /nologo ###.csproj
Writing '###.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=###\AppData\Local\Temp\tmp739.tmp /verbosity:quiet /nologo ###.csproj
dotnet exec --depsfile ###\bin\Debug\net5.0\###.deps.json --additionalprobingpath ###\.nuget\packages --additionalprobingpath "C:\Program Files (x86)\DevExpress 20.2\Components\Offline Packages" --runtimeconfig ###\bin\Debug\net5.0\###.runtimeconfig.json ###\.dotnet\tools\.store\dotnet-ef\5.0.6\dotnet-ef\5.0.6\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll migrations script --idempotent --context MyAppDbContext -o migrations.sql --assembly ###\bin\Debug\net5.0\###.dll --startup-assembly ###\bin\Debug\net5.0\###.dll --project-dir ### --language C# --working-dir ### --verbose --root-namespace MyApp
Using assembly 'MyApp'.
Using startup assembly 'MyApp'.
Using application base '###\bin\Debug\net5.0'.
Using working directory '###'.
Using root namespace 'MyApp'.
Using project directory ###'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Found IDesignTimeDbContextFactory implementation 'MyAppDbContextFactory'.
Found DbContext 'MyAppDbContext'.
Finding application service provider in assembly 'MyApp'...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Staging'.
Using application service provider from Microsoft.Extensions.Hosting.
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
   at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
   at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
   at MyApp.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in ###\MyApp\Startup.cs:line 41
   at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_0`2.<AddDbContext>b__0(IServiceProvider p, DbContextOptionsBuilder b)
   at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
   at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass17_0`1.<AddCoreServices>b__0(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__17`1.<AddCoreServices>b__17_1(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetServices[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextTypes()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextType(String name)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.ScriptMigration(String fromMigration, String toMigration, MigrationsSqlGenerationOptions options, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigrationImpl(String fromMigration, String toMigration, Boolean idempotent, Boolean noTransactions, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Value cannot be null. (Parameter 'connectionString')

Include provider and version information

EF Core version: 5.0.6 Entity Framework Core .NET Command-line Tools 5.0.6 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 5.0 Operating system: Windows 10 IDE: Visual Studio 2019 16.9.4

Pretty sure it is environment independent as I have the same issue on a linux build server.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:8
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
bricelamcommented, Jun 15, 2021
  1. We should probably remove the Check.NotEmpty() call since #8427 was intended to defer the validation of connection strings
  2. We should probably swallow exceptions thrown by services.GetServices<DbContextOptions>() since it is just one of many ways we use to resolve the context name to an actual type.
0reactions
tecxxcommented, Jun 2, 2023

Not sure if I’m experiencing the same problem, but migrations remove specifically does not use the IDesignTimeDbContextFactory in my case.

> dotnet ef migrations add Indexes && dotnet format whitespace
Build started...
Build succeeded.
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.
Done. To undo this action, use 'ef migrations remove'
> dotnet ef migrations remove        
Build started...
Build succeeded.
System.InvalidOperationException: A relational store has been configured without specifying either the DbConnection or connection string to use.
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   ...

i believe i run into the same issue. add-migration works, but remove-migration runs into sql connection timeout.

Read more comments on GitHub >

github_iconTop Results From Across the Web

getting DesignTimeDbContextFactory to run migrations ...
Probably something is wrong with your class implementing IDesignTimeDbContextFactory which prevents EF Core finding/using it. Run Add-Migration ...
Read more >
Add an implementation of IDesignTimeDbContextFactory
You are trying to add new migration and update database, and you are running into this error: Unable to create an object of...
Read more >
You don't need a IDesignTimeDbContextFactory - André Snede
Fixing this error -> Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project.
Read more >
Design-time DbContext Creation - EF Core
Some of the EF Core Tools commands (for example, the Migrations commands) require a derived DbContext instance to be created at design time ......
Read more >
IDesignTimeDbContextFactory<TContext> Interface
A factory for creating derived DbContext instances. Implement this interface to enable design-time services for context types that do not have a public ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found