Unable to create an object of type '[DBContext's Name]'. For the different patterns supported at design time

asp.netasp.net MvcEntity FrameworkEntity Framework-CoreEntity Framework-Migrations

asp.net Problem Overview


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

asp.net Solutions


Solution 1 - asp.net

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 - asp.net

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 - asp.net

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 - asp.net

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 - asp.net

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": "*"
}

Solution 6 - asp.net

It's not really an issue with the framework, it's how you built your application. For example, if you used DI and you had the WebApi (or the MVC project) separeted from your data access layer, this will occur to you because when you try to add a migration, you context cant find the connection string that you're trying to inject (this actually was my case).

A good explanation is found here on GitHub:

> That's definitely not an app issue which is this scope of the issues in this repo, but > I'll try to give you some guidance anyway. > >You get that error because to generate migrations you need either: > > 1) A DbContext with a default constructor (that is, a parameterless constructor) > > 2) Being able to get the DbContext from ApplicationServices (that is, Dependency Injection) > 3) A design time factory that returns a properly configured DbContext. > >Since ApplicationDbContext constructor has a parameter, you have to use options 2 or 3. See the details in the article: https://docs.microsoft.com/ef/core/miscellaneous/cli/dbcontext-creation > > But option 2 (the one originally used) doesn't work any more, because the program startup was changed to improve logging. > > And, since there's no DesignTimeFactory for ApplicationDbContext you just won't be able to create migrations at this time. > > If you want to learn about this way for creating migrations you can: > > Create an ApplicationDbContextDesignTimeFactory, similar to CatalogContextDesignFactory > or IntegrationEventLogContextDesignTimeFactory, or > Try with other microservice like Catalog.API, that already has its DesignTimeFactory.

Solution 7 - asp.net

I got this error after placing my DbContext in a separate class library using .NET Core 3.1.

Final solution looked like this that picked up my connection string from my original applications appsettings.json:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace MyNamespace
{
    public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();

            var optionsBuilder = new DbContextOptionsBuilder();

            var connectionString = configuration
                        .GetConnectionString("DefaultConnection");

            optionsBuilder.UseSqlServer(connectionString);

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

I could then use this in my other project like this:

var applicationDbContextFactory = new ApplicationDbContextFactory();

using (var dbContext = applicationDbContextFactory.CreateDbContext(args))
{
    
}

Solution 8 - asp.net

In StartUp file ConfigureServices method

services.AddDbContextPool<contextName>(
                    options => options.UseSqlServer(Configuration.GetConnectionString("conString")));

Solution 9 - asp.net

If you are using a properly authenticated database server like Azure SQL DB, check whether you replace the Password={your_password} with your server password in your connection string.

Solution 10 - asp.net

this is one of the most nonsense issues you'd ever encounter with ASP.NET Core. I am not really sure about the course you mentioned but if your application is just like mine where presentation layer is segregated from data layer; make sure that you install the latest version of Microsoft.EntityFrameworkCore.Design on your presentation layer too "your startup project". It is required, and the error message says nothing about it.

Solution 11 - asp.net

If your startup project uses the ASP.NET Core Web Host or .NET Core Generic Host, the tools try to obtain the DbContext object from the application's service provider, otherwise you could create the DbContext from a design-time factory (https://docs.microsoft.com/es-es/ef/core/miscellaneous/cli/dbcontext-creation).

Solution 12 - asp.net

In my case, I made the appsettings.development.json file mandatory but I didn't create the file. If you are not creating the enviroment specific setting file, set it as optional: true

var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

But, it is important to note that the error may not necessarily related to the DbContext and its configurations. It could be some other error in your application startup which prevents the app from booting up so that the EF tooling can do the migration. As a mechanism to locate any other error in your project startup, you can add console message at various lines of your Startup. You can even inspect appsetting values like connectionstrings using console while trying to migrate.

 Console.WriteLine("I can see this because the app was able to proceed this far."); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOoMaR jOhUrView Question on Stackoverflow
Solution 1 - asp.netBaqer NaqviView Answer on Stackoverflow
Solution 2 - asp.nettonymayoralView Answer on Stackoverflow
Solution 3 - asp.netImaginaryRView Answer on Stackoverflow
Solution 4 - asp.nettomRedoxView Answer on Stackoverflow
Solution 5 - asp.netLeonardo LimaView Answer on Stackoverflow
Solution 6 - asp.netLuisView Answer on Stackoverflow
Solution 7 - asp.netOgglasView Answer on Stackoverflow
Solution 8 - asp.netA.MudithaView Answer on Stackoverflow
Solution 9 - asp.netMalithView Answer on Stackoverflow
Solution 10 - asp.netSaajid AkramView Answer on Stackoverflow
Solution 11 - asp.netEBPView Answer on Stackoverflow
Solution 12 - asp.netyibeView Answer on Stackoverflow