我有错误:InvalidOperationException:尝试激活控制器时无法解析类型服务

问题描述 投票:0回答:1

我用 EF 6.0 制作网页时出现错误。


InvalidOperationException: Unable to resolve service for type 'WebbyMyself.Models.StudentManageEntities' while attempting to activate 'WebbyMyself.Controllers.BranchesController'.

有模型/StudentManageEntities.cs

using Microsoft.EntityFrameworkCore;

namespace WebbyMyself.Models
{
    public class StudentManageEntities : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBulder)
        {
            optionsBulder.UseSqlServer(
                "*connetion string of my database*"
            );
        }
        public virtual DbSet<Branch> Branch { get; set; }
    }
}

Controllers/BranchController.cs:

`using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebbyMyself.Models;

namespace WebbyMyself.Controllers
{
    public class BranchController : Controller
    {
        private readonly StudentManageEntities _context;

        public BranchController(StudentManageEntities context)
        {
            _context = context;
        }

        // GET: Branch
        public async Task<IActionResult> Index()
        {
              return View(await _context.Branch.ToListAsync());
        }
    }
}

Views/Branch/Index.cshtml:

@model IEnumerable<WebbyMyself.Models.Branch>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>                            
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.BranchName)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.BranchName)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

我在 Visual Studio 2022 中使用代码生成。

我不知道如何修复,所以请帮助我。 ;-;

*我不知道如何描述,所以如果您想了解更多信息,请告诉我。 ;-;非常感谢。*

c# entity-framework model-view-controller entity-framework-core entity-framework-6
1个回答
0
投票

您需要在 Program.cs 文件中使用名称“StudentManageEntities”注册您的 DbContext:

services.AddDbContext<ShopDbContext>(options =>
    options.UseSqlServer(configuration.GetConnectionString("ShopSqlConnectionString1")));
© www.soinside.com 2019 - 2024. All rights reserved.