无法创建“[DBContext 的名称]”类型的对象。对于设计时支持的不同模式[关闭]

Posted

技术标签:

【中文标题】无法创建“[DBContext 的名称]”类型的对象。对于设计时支持的不同模式[关闭]【英文标题】:Unable to create an object of type '[DBContext's Name]'. For the different patterns supported at design time [closed] 【发布时间】:2019-08-03 01:34:18 【问题描述】:

我正在关注 Udemy 中关于 ASP.NET MVC 的 Mosh Hamedani 课程之一。

我在使用代码优先(实体框架)设计数据库时遇到了一个错误。

一开始我得到“No DbContext was found in assembly”的错误。解决了这个问题后,另一个不知从何而来。

下图将显示添加迁移时发现的错误。我已经搜索过相同的错误但徒劳无功。过去两个小时我一直在苦苦挣扎,但到现在都没有解决。

请有人帮帮我。谢谢

无法创建“Vidly_Context”类型的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728


使用 (2) 参数添加自己的 DbContext 构造函数后出现类似问题。应用程序正常,但迁移停止工作。 通过使用来自 Dotnet tool @xspdf 的信息并通过方法 + 硬编码的默认连接字符串(如果未设置)替换提到的构造函数,通过第一次更新 EF(使用 5 时出于奇怪的原因使用 3.1.5)修复。

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 & 上下文激活错误

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

【问题讨论】:

你读过给定的链接吗? 是的,它现在可以工作了。一段 C# 代码将被添加到启动文件中 @OoMaRjOhUr 您可以添加一个答案,显示您添加了哪些代码以使其正常工作,然后接受该答案。这可能会在将来对某人有所帮助。 是的,为什么不@OoMaRjOhUr 添加答案以便其他人可以看到? 尝试在debug模式下运行app,在dbcontext注入到di容器之前看看app是否抛出异常。应用程序在“options.UseSqlServer(.)”之前引发了同样的问题。我希望这会有所帮助 【参考方案1】:

1- 确保将您的网络项目设置为设置为启动项目

2- 在 Package Manager Console 中,将您的数据访问层(如果有)设置为 默认 项目

3- 然后再次运行命令

【讨论】:

值得一提的是,如果您在没有“设置为启动项目”的情况下使用 Rider,则可以在命令中使用 --startup-project 这会导致错误“您的启动项目 'Web' 没有引用 Microsoft.EntityFrameworkCore.Design。”因此,关于关注点分离,我不希望我的 Web 项目了解 EF ..... 我遇到了一个完全不同的问题,导致了同样的错误。使用 -verbose 标志运行 Add-Migration 非常有用,因此您可以了解为什么它无法生成迁移。在我的情况下,它是 DBContext 缺少的空构造函数。 有时也可能是工具过时 @JHBonarius 你有什么解决办法吗?【参考方案2】:

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

例如:

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

【讨论】:

已更新。第二个命令是指定了启动项目标志的迁移命令示例。应该与任何迁移命令一起使用。 IMO 是比现有答案更好的方法,因为它不需要更改您的代码 添加 --startup-project 为我解决了这个问题,谢谢! 这也为我做了。我的连接字符串在我的 appsettings.json 中,它在我的主 web api 项目中,它与我的数据项目(dbcontext 所在的位置)是分开的。我在我的数据项目中运行 dotnet ef migrations add InitialCreate ,但由于原始帖子中报告的错误而失败。一旦我添加了 --startup-project 和我的主 web api 项目的路径,它就起作用了。【参考方案3】:

我遇到了同样的问题。 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>();

为我的数据库上下文添加此内容后,问题已解决。

【讨论】:

【参考方案4】:

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

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

通过阅读documentation page linked to by the error message 并比较两个项目的 startup.cs 文件中的代码,我不确定为什么会这样,但暂时将启动项目切换到 MVC 项目可以解决这个问题。

【讨论】:

您的问题是否是由于在 MVC 项目中引用了 Microsoft.EntityFrameworkCore.Design 而不是 Blazor 项目引起的?我发现过去就是这种情况。 @PTD 我很晚才尝试添加该引用,但它并没有为我修复它。【参考方案5】:

我收到此错误是因为我的 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": "*"

【讨论】:

我遇到了类似的问题。作为建议,请确保您的程序运行,或至少在尝试修复“添加迁移”问题之前启动【参考方案6】:

这不是框架的真正问题,而是您构建应用程序的方式。例如,如果您使用 DI 并且您将 WebApi(或 MVC 项目)与数据访问层分离,您会遇到这种情况,因为当您尝试添加迁移时,您的上下文找不到您正在使用的连接字符串尝试注入(这实际上是我的情况)。

在GitHub 上找到了一个很好的解释:

这绝对不是一个应用程序问题,这是这个 repo 中问题的范围,但是 无论如何,我会尽力给你一些指导。

您会收到该错误,因为要生成迁移,您需要:

    具有默认构造函数(即无参数构造函数)的 DbContext

    能够从ApplicationServices获取DbContext(即依赖注入)

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

由于ApplicationDbContext构造函数有参数,所以必须使用选项2或3。详情见文章:https://docs.microsoft.com/ef/core/miscellaneous/cli/dbcontext-creation

但是选项 2(最初使用的那个)不再起作用,因为更改了程序启动以改进日志记录。

而且,由于 ApplicationDbContext 没有 DesignTimeFactory,所以此时您将无法创建迁移。

如果您想了解这种创建迁移的方法,您可以:

创建一个 ApplicationDbContextDesignTimeFactory,类似于 CatalogContextDesignFactory > 或 IntegrationEventLogContextDesignTimeFactory,或 尝试使用其他已经拥有 DesignTimeFactory 的微服务,例如 Catalog.API。

【讨论】:

是的,这就是我的情况。我在迁移后添加了 DI,并且 DbContext 在设计时变得无法访问。通过将选项移动到 DbContext 的 OnConfigiring 方法使 DbContext 无参数来解决【参考方案7】:

在使用 .NET Core 3.1 将我的 DbContext 放入单独的类库后,我收到此错误。

最终解决方案看起来像这样,它从我的原始应用程序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))

    

【讨论】:

所以不可能在类库的设置文件中配置 dbcontext 和连接字符串? 你是对的。在我的情况下,我只是注释行“new ConfigurationBuilder()...”并且它可以工作。【参考方案8】:

在启动文件中的ConfigureServices方法

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

【讨论】:

我正在使用这个,但仍然收到错误【参考方案9】:

如果您使用的是经过正确身份验证的数据库服务器,例如 Azure SQL DB,请检查您是否将连接字符串中的 Password=your_password 替换为您的服务器密码。

【讨论】:

【参考方案10】:

这是您在使用 ASP.NET Core 时遇到的最无意义的问题之一。我不太确定您提到的课程,但是如果您的应用程序就像我的一样,表示层与数据层分离;确保在表示层上安装最新版本的 Microsoft.EntityFrameworkCore.Design 也是“你的启动项目”。它是必需的,并且错误消息没有说明它。

【讨论】:

晦涩难懂。我选择了这个选项,一切都很好 - 谢谢。 在收到上述错误之前,我收到一条错误消息,说 API 层需要包 Microsoft.EntityFrameworkCore.Design,因此不再是这种情况了。【参考方案11】:

如果您的启动项目使用 ASP.NET Core Web Host 或 .NET Core Generic Host,工具会尝试从应用程序的服务提供者获取 DbContext 对象,否则您可以从设计时工厂(@ 987654321@).

【讨论】:

【参考方案12】:

就我而言,我将 appsettings.development.json 文件设为强制性文件,但我没有创建该文件。如果您没有创建环境特定的设置文件,请将其设置为 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();

但是,重要的是要注意错误可能不一定与 DbContext 及其配置有关。可能是您的应用程序启动中的一些其他错误导致应用程序无法启动,以便 EF 工具可以进行迁移。作为在项目启动中定位任何其他错误的机制,您可以在 Startup 的各个行添加控制台消息。您甚至可以在尝试迁移时使用控制台检查 appsetting 值,例如连接字符串。

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

【讨论】:

以上是关于无法创建“[DBContext 的名称]”类型的对象。对于设计时支持的不同模式[关闭]的主要内容,如果未能解决你的问题,请参考以下文章

为返回对的对创建模板类[重复]

binlog2sql的对MySQL列的兼容性测试

MySQL 数据库MySQL 的对库的操作及其数据类型

Coq 数据类型 - 一对带括号的对

OpenCV中将MAT类型的对象作为InputArray类型的对像传递给函数

一道面试题引发的对javascript类型转换的思考