尝试自学MVC。我首先在MVC模式中使用数据库。我已经搭建了控制器和视图。然而,当我运行它时,我得到了这个错误?我不知道该怎么做,因为这是通过自动生成的。
InvalidOperationException: Unable to resolve service for type 'OPPS_APP11_7_2020.Models.ENT_PLANNERContext' while attempting to activate 'OPPS_APP11_7_2020.Controllers.ProductsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)发布于 2020-11-08 12:14:02
似乎在ProductController构造函数中有数据库上下文,而在configureServices中却没有使用startup.cs中的依赖项注入(DI)进行注册。如果您不熟悉ASP.Net核心中依赖项注入,建议您阅读一下MS Docs
如果你正在使用实体框架(EF),有一些特殊的方法可以在DI中添加它们的上下文。检查此Configuring a DbContext in EF Core, Ms Docs
发布于 2020-11-09 13:57:30
在使用Scaffold-DbContext命令基于现有数据库生成相关模型和dbcontext之后,必须在启动的ConfigureServices方法中将DbContext注册为依赖项注入。
尝试添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//register the dbcontext.
services.AddDbContext<ENT_PLANNERContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}您可以在appsetting.json文件中添加连接字符串:
"ConnectionStrings": {
"DefaultConnection": "{your database connection string}"
}参考资料:
https://www.entityframeworktutorial.net/efcore/create-model-for-existing-database-in-ef-core.aspx
https://stackoverflow.com/questions/64734623
复制相似问题