微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

InvalidOperationException:MVC

如何解决InvalidOperationException:MVC

尝试自学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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。