Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 无效操作异常:MVC_Asp.net Mvc_Asp.net Core - Fatal编程技术网

Asp.net mvc 无效操作异常:MVC

Asp.net mvc 无效操作异常:MVC,asp.net-mvc,asp.net-core,Asp.net Mvc,Asp.net Core,试着自学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.P

试着自学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.NETCore中的依赖项注入,我建议您阅读一下,查看


如果您使用的是实体框架(EF),那么有一种特殊的方法可以在DI中添加它们的上下文。选中此项

在使用
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")));
    }
参考:

  "ConnectionStrings": {
    "DefaultConnection": "{your database connection string}"
  }