Closed ScottKane closed 2 years ago
@ScottKane Nothing obvious. If you run the EF application and use context.Database.EnsureCreated
, does it also fail? Or is it only using the migration command line?
@ajcvickers Using EnsureCreated the app starts fine and the DB is successfully created, seems to just be an issue with migrations.
Looking at following part in exception message
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at GrpcAuth.Infrastructure.DatabaseSeeder.<AddAdministrator>b__6_0() in D:\Repos\GrpcAuth\Infrastructure\DatabaseSeeder.cs:line 45
at GrpcAuth.Infrastructure.DatabaseSeeder.AddAdministrator() in D:\Repos\GrpcAuth\Infrastructure\DatabaseSeeder.cs:line 39
at GrpcAuth.Infrastructure.DatabaseSeeder.Seed() in D:\Repos\GrpcAuth\Infrastructure\DatabaseSeeder.cs:line 32
at GrpcAuth.Server.Extensions.ApplicationBuilderExtensions.SeedDatabase(IApplicationBuilder app) in D:\Repos\GrpcAuth\Server\Extensions\ApplicationBuilderExtensions.cs:line 11
at GrpcAuth.Server.Program.<>c.<Main>b__1_2(WebHostBuilderContext _, IApplicationBuilder app) in D:\Repos\GrpcAuth\Server\Program.cs:line 90
at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_1.<Configure>b__2(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.DelegateStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure' to the 'UseSqlServer
' call.
Unable to create an object of type 'ApplicationContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
The application startup seems to be seeding database which is running a query against a database which doesn't exist. So through hosting context creation is supposed to throw this exception. But last line indicates that there is no other way that we could find to create context. Likely bad code in startup.
Ok I've disabled the seeder for now but adding the migration now just runs the application which doesn't result in a migration being scaffolded:
dotnet ef migrations add Initial -p Infrastructure\Infrastructure.csproj -s Server\Server.csproj
Build started...
Build succeeded.
Hosting environment: Development
Content root path: D:\Repos\GrpcAuth\Server
Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
Application started. Press Ctrl+C to shut down.
I'm using the following style startup code:
internal static class Program
{
private static IConfiguration _configuration = null!;
private static async Task Main() =>
await WebHost.CreateDefaultBuilder()
.UseStaticWebAssets()
.ConfigureAppConfiguration((_, configuration) => _configuration = configuration.Build())
.ConfigureServices(services =>
{
services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
services
.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>()
.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>()
.AddIdentity<ApplicationUser, ApplicationRole>(
options =>
{
options.Password.RequiredLength = 6;
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationContext>()
.AddDefaultTokenProviders();
})
.Configure((_, app) =>
{
app.Use...
})
.Build()
.RunAsync();
}
My other application uses the UseStartup approach and never had this happen while creating a migration but I can't imagine that is the issue here
Or is this because I had used EnsureCreated and I now need to delete that DB?
Or is this because I had used EnsureCreated and I now need to delete that DB?
This. The database already exist then error is not thrown and startup would work fine.
I just tried deleting the DB and running the migration again but it just starts the application and doesn't scaffold the migration
@ScottKane
My other application uses the UseStartup approach and never had this happen while creating a migration but I can't imagine that is the issue here
This is likely the issue. See https://github.com/dotnet/efcore/issues/28105
/cc @davidfowl
@ajcvickers That issue mentions that switching to CreateDefaultBuilder
resolves the issue but that's what I'm using and I still get it
Full verbose logs in case it's helpful:
dotnet ef migrations add Initial -p Infrastructure\Infrastructure.csproj -s Server\Server.csproj -v
Using project 'D:\Repos\GrpcAuth\Infrastructure\Infrastructure.csproj'.
Using startup project 'D:\Repos\GrpcAuth\Server\Server.csproj'.
Writing 'D:\Repos\GrpcAuth\Infrastructure\obj\Infrastructure.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\scott\AppData\Local\Temp\tmpEF41.tmp /verbosity:quiet /nologo D:\Repos\GrpcAuth\Infrastructure\Infrastructure.csproj
Writing 'D:\Repos\GrpcAuth\Server\obj\Server.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\scott\AppData\Local\Temp\tmpF0E8.tmp /verbosity:quiet /nologo D:\Repos\GrpcAuth\Server\Server.csproj
Build started...
dotnet build D:\Repos\GrpcAuth\Server\Server.csproj /verbosity:quiet /nologo
Build succeeded.
-------- NULLABLE WARNINGS OMITTED FOR BREVITY --------
33 Warning(s)
0 Error(s)
Time Elapsed 00:00:04.84
Build succeeded.
dotnet exec --depsfile D:\Repos\GrpcAuth\Server\bin\Debug\net6.0\Server.deps.json --additionalprobingpath C:\Users\scott\.nuget\packages --runtimeconfig D:\Repos\GrpcAuth\Server\bin\Debug\net6.0\Server.runtimeconfig.json C:\Users\scott\.dotnet\tools\.store\dotnet-ef\6.0.6\dotnet-ef\6.0.6\tools\net6.0\any\t
ools\netcoreapp2.0\any\ef.dll migrations add Initial --assembly D:\Repos\GrpcAuth\Server\bin\Debug\net6.0\Infrastructure.dll --project D:\Repos\GrpcAuth\Infrastructure\Infrastructure.csproj --startup-assembly D:\Repos\GrpcAuth\Server\bin\Debug\net6.0\Server.dll --startup-project D:\Repos\GrpcAuth\Server\Se
rver.csproj --project-dir D:\Repos\GrpcAuth\Infrastructure\ --root-namespace GrpcAuth.Infrastructure --language C# --framework net6.0 --nullable --working-dir D:\Repos\GrpcAuth --verbose
Using assembly 'Infrastructure'.
Using startup assembly 'Server'.
Using application base 'D:\Repos\GrpcAuth\Server\bin\Debug\net6.0'.
Using working directory 'D:\Repos\GrpcAuth\Server'.
Using root namespace 'GrpcAuth.Infrastructure'.
Using project directory 'D:\Repos\GrpcAuth\Infrastructure\'.
Remaining arguments: .
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'Server'...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Hosting environment: Development
Content root path: D:\Repos\GrpcAuth\Server
Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
Application started. Press Ctrl+C to shut down.
Application is shutting down...
System.InvalidOperationException: The entry point exited without ever building an IHost.
at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.CreateHost()
at Microsoft.Extensions.Hosting.HostFactoryResolver.<>c__DisplayClass10_0.<ResolveHostFactory>b__0(String[] args)
at Microsoft.Extensions.Hosting.HostFactoryResolver.<>c__DisplayClass13_0.<ResolveServiceProviderFactory>b__3(String[] args)
at Microsoft.EntityFrameworkCore.Design.Internal.AppServiceProviderFactory.CreateFromHosting(String[] args)
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: The entry point exited without ever building an IHost.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'ApplicationContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ApplicationContext'. 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[GrpcAuth.Infrastructure.Contexts.ApplicationContext]' while attempting to activate 'GrpcAuth.Infrastructure.Contexts.ApplicationContext'.
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__DisplayClass21_4.<FindContextTypes>b__13()
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_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.AddMigration(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>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)
Unable to create an object of type 'ApplicationContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
I can confirm that after switching to UseStartup
. Migrations run as expected
Duplicate of https://github.com/dotnet/efcore/issues/28105
I'm adding an initial migration to a new application, EF fails stating it can't connect to the database using the following connection string:
This DB context and configuration was migrated from an existing app which works fine.
I noticed part of the error mentions
Login failed for user 'SCOTTS-PC\scott'.
however this is the same credential used in another app to access a localdb which works fine. Am I missing something obvious here?EF Core version: 6.0.6 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: NET 6.0 Operating system: Windows 11 IDE: Rider 2022.1.2