OoM*_*hUr 56 asp.net asp.net-mvc entity-framework entity-framework-core entity-framework-migrations
我正在 Udemy 中学习有关 ASP.NET MVC 的 Mosh Hamedani 课程之一。
我在使用代码优先(实体框架)设计数据库时遇到了一个错误。
起初,我收到了“在程序集中找不到 DbContext”的错误消息。解决了这个问题后,又一个突然冒出来了。
下图将显示添加迁移时发现的错误。我已经搜索了相同的错误,但没有找到。我在过去的两个小时里一直在挣扎,但到目前为止还没有解决任何问题。
无法创建“Vidly_Context”类型的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728
使用 (2) 参数添加自己的 DbContext 构造函数后出现类似问题。应用程序正常,但迁移停止工作。通过使用来自Dotnet 工具 @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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Baq*_*qvi 55
1- 确保将您的 web 项目设置为 Set as Startup Project
2- 在Package Manager Console 中,将您的数据访问层(如果有)设置为默认项目
3-然后再次运行命令
小智 22
我遇到了同样的问题。OP 提到他们需要将代码添加到他们的 Startup.cs。
在https://go.microsoft.com/fwlink/?linkid=851728 上有以下代码示例;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
=> services.AddDbContext<ApplicationDbContext>();
}
Run Code Online (Sandbox Code Playgroud)
我的代码在我的 ConfigureServices 方法中缺少以下内容;
services.AddDbContext<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)
在为我的数据库上下文添加这个之后,问题就解决了。
ton*_*ral 22
该错误消息指出无法在设计时创建上下文。如果您在迁移命令中使用 --startup-project 标志(或 -s)指定启动项目,您可以帮助该命令在设计时创建上下文实例,其方式与在运行时创建的方式类似。
例如:
cd ./project_with_migrations_folder
dotnet ef --startup-project ../my_startup_project_path/ migrations add myMigration01
Run Code Online (Sandbox Code Playgroud)
Ogg*_*las 13
使用 .DbContext 将 DbContext 放入单独的类库中后出现此错误.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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以在我的其他项目中使用它,如下所示:
var applicationDbContextFactory = new ApplicationDbContextFactory();
using (var dbContext = applicationDbContextFactory.CreateDbContext(args))
{
}
Run Code Online (Sandbox Code Playgroud)
小智 9
在启动文件中的ConfigureServices方法中
services.AddDbContextPool<contextName>(
options => options.UseSqlServer(Configuration.GetConnectionString("conString")));
Run Code Online (Sandbox Code Playgroud)
我收到此错误是因为我的 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": "*"
}
Run Code Online (Sandbox Code Playgroud)
这不是框架的真正问题,而是您构建应用程序的方式。例如,如果您使用 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,或者尝试使用其他微服务,如 Catalog.API,已经有它的 DesignTimeFactory。
这是您在 ASP.NET Core 中遇到的最无意义的问题之一。我不太确定你提到的课程,但如果你的应用程序和我的应用程序一样,表示层与数据层分离;确保在表示层“您的启动项目”上安装最新版本的 Microsoft.EntityFrameworkCore.Design。这是必需的,并且错误消息对此没有任何说明。
| 归档时间: |
|
| 查看次数: |
63532 次 |
| 最近记录: |