问题描述
尝试自学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)
解决方法
似乎ProductController构造函数中有数据库上下文,而未在configureServices中的startup.cs中使用依赖注入(DI)进行注册。 如果您不熟悉ASP.Net核心中的依赖项注入,建议您阅读有关内容,请检查MS Docs
如果您正在使用实体框架(EF),则可以使用特殊方法在DI中添加其上下文。检查此Configuring a DbContext in EF Core,Ms Docs
,在使用Scaffold-DbContext
命令基于现有数据库生成关联模型和dbcontext之后,必须在Startup的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