Unable to create an object of type '[DBContext's Name]'. For the different patterns supported at design time
Solution 1
1- Make sure to set your web project as Set as Startup Project
2- In Package Manager Console, set your data access layer (if any) as a default project
3- Then run the command again
Solution 2
The error message states that the context could not be created at design time. If you specify in the migration command the startup project with the --startup-project flag (or -s) you can help the command create the context instance at design time in a similar way to how it would be created at run time.
For example:
cd ./project_with_migrations_folder
dotnet ef --startup-project ../my_startup_project_path/ migrations add myMigration01
Solution 3
I ran into the same issue. OP mentioned they needed to add code to their Startup.cs.
On https://go.microsoft.com/fwlink/?linkid=851728 there's the following code sample;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
=> services.AddDbContext<ApplicationDbContext>();
}
My code was missing the following in my ConfigureServices method;
services.AddDbContext<ApplicationDbContext>();
After adding this for my database context the issue was resolved.
Solution 4
I ran into this issue when using EF Core code-first migrations in a .NET Core 3 solution that contained both an MVC project and a Blazor project.
If I have the solution's startup project set to the Blazor project I get the error when using add-migration
, but I don't if I have the startup project set to the MVC project.
From reading the documentation page linked to by the error message and comparing the code in the startup.cs files for both projects I'm not sure why that would be, but temporarily switching the startup project to the MVC project fixes it for me.
Solution 5
I got this error because a comma was missing in my appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=Leonardo-Notebook;Initial Catalog=MyDB;Integrated Security=True"
}, // <- Comma missing here
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Related videos on Youtube
Comments
-
OoMaR jOhUr over 2 years
I'm following one of Mosh Hamedani Course on ASP.NET MVC in Udemy.
I came across one error while designing my Database using code-first (Entity Framework).
At first, I got the error of " No DbContext was found in assembly". After resolving this problem another one surged from nowhere.
The image below will show you the error found while adding a migration. I've already searched for the same error but in vain. I'm struggling for the past two hours but nothing is solved till now.
Please, someone, help me. Thanks
unable to create an object of type 'Vidly_Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Similar problem after adding own DbContext constructor with (2) parameters. App was ok, but migrations stopped working. Fixed by 1st updating EF (3.1.5 used for strange reason when working with 5) using info from Dotnet tool @xspdf and replacing mentioned constructor by method + hardcoded default connection string if not set.
dotnet tool update --global dotnet-ef // following command show the most during migration build/run in cmd // mind current dir is Migrations folder of (VS) startup project here dotnet ef --startup-project ../ --verbose migrations add test
3.1.5 & context activation Error
The Entity Framework tools version '3.1.5' is older than that of the runtime '5.0.0'. Update the tools for the latest features and bug fixes. Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider in assembly '...'... 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 '...Context'. Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type '...Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate '...'. (my additional parameter) 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.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 '...Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
-
tschmit007 about 5 yearshave you read the given link ?
-
OoMaR jOhUr about 5 yearsYes, its now working. A piece of C# code was to be added to the Startup file
-
tomRedox almost 5 years@OoMaRjOhUr you could add an answer showing what code you added to get this working and then accept that answer. That might help someone in future.
-
Ted about 4 yearsYes, why dont @OoMaRjOhUr add the answer so the rest can see it?
-
Dennis Kabugua over 2 yearsTry running the app in debug mode and see whether the application throws an exception before before the dbcontext is injected into the di container. Had the same problem caused by the application throwing before "options.UseSqlServer(.)"..I hope this helps
-
Davud Seyfullayev about 2 yearsin Program.cs add "var app = builder.Build();" this line after builder.Services.AddDbContex
-
-
Shahriar Rahman Zahin almost 4 yearsI'm using exactly this, but still getting the error
-
tonymayoral over 3 yearsUpdated. The second command is an example of a migrations command with the startup-project flag specified. Should work with any migrations command. IMO is a better approach than existing answers because it doesn't require changing your code
-
scottdavidwalker over 3 yearsWorthwhile to mention that if you use Rider where you don't have a "Set as Startup Project" you can use --startup-project on the command
-
SykoTron over 3 yearsso it is not possible to have a dbcontext and a connection string configured in a settings file in a class lib?
-
Scott Willis over 3 yearsObscure it is. I went for this option and all was good - thanks.
-
Miguel Hughes over 3 yearsI had a similar problem than this. As a suggestion, make sure your program runs, or at least starts before trying to fix the "add-migrations" problem
-
JHBonarius over 3 yearsThis causes the error "Your startup project 'Web' doesn't reference Microsoft.EntityFrameworkCore.Design." So regarding separation of concerns, I don't want my Web project to know about EF.....
-
Niksr about 3 yearsYes, this was my case. I added DI after migrations and DbContext became inaccessible on design time. Solved by making DbContext parametrless by moving options to the OnConfigiring method of DbContext
-
Mocas almost 3 yearsBefore getting the error above, I was getting an error saying that the package Microsoft.EntityFrameworkCore.Design is needed in the API layer, so this is not the case anymore.
-
GeorgiG almost 3 yearsI had an entirely different problem resulting in the same error. It is very useful to run Add-Migration with -verbose flag so you can see why it fails to generate migration. In my case it was a missing empty constructor for DBContext.
-
Nguyễn Ngọc Anh almost 3 yearsyou are right. in my case i just comment line "new ConfigurationBuilder()..." and it work.
-
c-sharp-and-swiftui-devni over 2 yearsSometimes it can be the tooling out of date as well
-
badsyntax over 2 yearsAdding
--startup-project
fixed it for me, thanks! -
PTD over 2 yearsCould your issue have been caused by having a reference to
Microsoft.EntityFrameworkCore.Design
in the MVC project but not the Blazor project? I have found this to be the case in the past. -
Andrew over 2 yearsThis did it for me too. My connection string is in my appsettings.json, which is in my main web api project, which is separate from my data project (where the dbcontext lives). I was running dotnet ef migrations add InitialCreate in my data project, and it was failing with the error reported in the original post. Once I added --startup-project and the path to my main web api project, it worked.
-
Aijaz Chauhan over 2 years@JHBonarius did you get any solution for that?
-
tomRedox over 2 years@PTD I've very belatedly just tried adding that reference, but it didn't fix it for me.
-
Arnout Pullen about 2 yearsPassing the params --startup-project=Project.WebApi and --project=Project.Data worked for me
-
martinoss almost 2 yearsAfter a fresh clone, I got the more meaningful error: Your startup project 'Xyz.Job' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.