Home > database >  How do I resolve an Entity Framework error creating the db context
How do I resolve an Entity Framework error creating the db context

Time:02-11

I have created my first (Blazer) project with Entity Framework. I got enable-migrations and update-database to work. Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton
ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

enter image description here

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction. Here is the db service in my startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}

I just have no idea where to go next. Any suggestions are appreciated.

CodePudding user response:

move your var app = builder.Build()line at the end of UseSqlServer line. first register all of your service then build the app.

CodePudding user response:

If you see an error like

"Unable to resolve service for type"

you must search the given unresolved type.

Unresolved type means, your middleware cannot identify what is the type given to him.

In this example Your services are in wrong order. Your builder cannot identify what is "Timesheet.Models.DatabaseContext".

So the solution seems you must call builder.Build() operation after builder.Configuration().

I suppose it helps when you see the same error at other times.

  • Related