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

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
176537 次浏览

中使用 EFCore 代码优先迁移时遇到了这个问题。NET Core 3解决方案,包含 MVC 项目和 Blazor 项目。

如果我将解决方案的启动项目设置为 Blazor 项目,那么在使用 add-migration时会得到错误,但是如果我将启动项目设置为 MVC 项目,则不会得到错误。

通过阅读 错误信息链接到的文档页和比较两个项目的 startup.cs 文件中的代码,我不确定为什么会这样,但是暂时将启动项目切换到 MVC 项目为我解决了这个问题。

确保将你的网络项目设置为 Set as Startup Project

包管理器控制台中,将数据访问层(如果有的话)设置为 违约项目

然后再次运行命令

我也遇到了同样的问题 OP 提到他们需要在 Startup.cs 中添加代码。

https://go.microsoft.com/fwlink/?linkid=851728上有以下代码示例;

public class Startup
{
public void ConfigureServices(IServiceCollection services)
=> services.AddDbContext<ApplicationDbContext>();
}

在 ConfigureServices 方法中,我的代码缺少以下内容;

services.AddDbContext<ApplicationDbContext>();

在为我的数据库上下文添加这个之后,问题就解决了。

在启动文件 ConfigureServices 方法中

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

我得到这个错误是因为 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": "*"
}

错误消息指出无法在设计时创建上下文。如果在迁移命令中指定带有—— start-project 标志(或-s)的启动项目,则可以帮助命令在设计时创建上下文实例,其方式与在运行时创建上下文实例的方式类似。

For example:

cd ./project_with_migrations_folder
dotnet ef --startup-project ../my_startup_project_path/ migrations add myMigration01

这是 ASP.NET Core 遇到的最无聊的问题之一。我不是很确定你提到的课程,但是如果你的应用程序和我的一样,表示层和数据层是分离的,确保你安装了最新版本的微软。实体框架核心。设计你的演示层也是“你的启动项目”。它是必需的,而错误消息没有提到它。

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

最终的解决方案看起来像这样,我的连接字符串从我的原始应用程序 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);
}
}
}

然后我可以在我的另一个项目中使用它,像这样:

var applicationDbContextFactory = new ApplicationDbContextFactory();


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

}

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:

这绝对不是一个应用程序的问题,这是这个问题的范围在这个回购,但 不管怎样,我会试着给你一些指导。

之所以会出现这个错误,是因为要生成迁移,您需要:

  1. 带有缺省构造函数的 dbContext (即无参数构造函数)

  2. 能够从 ApplicationServices 获取 dbContext (即依赖注入)

  3. 返回正确配置的 DbContext 的设计时工厂。

因为 ApplicationDbContext 构造函数有一个参数,所以必须使用选项2或3。请参阅文章中的细节: https://learn.microsoft.com/ef/core/miscellaneous/cli/dbcontext-creation

但是选项2(最初使用的选项)不再有效,因为程序启动被更改以改进日志记录。

而且,由于没有用于 ApplicationDbContext 的 DesignTimeFactory,因此此时无法创建迁移。

如果你想了解如何创建迁移,你可以:

创建 ApplicationDbContextDesignTimeFactory,类似于 CatalogContextDesignFactory > 或 IntegrationEventLogContextDesignTimeFactory,或 尝试使用其他微服务,如 Catalog.API,它已经有了自己的 DesignTimeFactory。

如果启动项目使用 ASP.NET 核心 Web 主机或。NET 核心泛型主机,这些工具尝试从应用程序的服务提供程序获取 DbContext 对象,否则您可以从设计时工厂(https://learn.microsoft.com/es-es/ef/core/miscellaneous/cli/dbcontext-creation)创建 DbContext。

In my case, I made the Appsetings.development.json file mandatory but I didn't create the file. If you are not creating the enviroment specific setting file, set it as 可选: 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();

但是,重要的是要注意错误 可能不一定与 DbContext 及其配置相关。可能是应用程序启动时出现了其他错误,导致应用程序无法启动,以便 EF 工具可以进行迁移。作为查找项目启动过程中其他错误的机制,您可以在启动过程的不同行添加控制台消息。在尝试迁移时,您甚至可以使用控制台检查 appset 值,如 Connectionstring。

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

如果您正在使用正确认证的数据库服务器(如 Azure SQL DB) ,请检查是否将 Password={your_password}替换为连接字符串中的服务器密码。