脚手架控制器class触发invalidoperationexception

Scafolded controller class trigger invalidoperationexception

我正在尝试学习一些 Web api 部分。因此创建了一个 EF,然后使用 DB 上下文创建了一个控制器。这是为我生成的控制器 .net。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SanApi.Models;

namespace SanApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TblDepartmentsController : ControllerBase
{
    private readonly ClassooContext _context;

    public TblDepartmentsController(ClassooContext context)
    {
        _context = context;
    }

    // GET: api/TblDepartments
    [HttpGet]
    public async Task<ActionResult<IEnumerable<TblDepartmentMaster>>> GetTblDepartmentMaster()
    {
        return await _context.TblDepartmentMaster.ToListAsync();
    }

    // GET: api/TblDepartments/5
    [HttpGet("{id}")]
    public async Task<ActionResult<TblDepartmentMaster>> GetTblDepartmentMaster(int id)
    {
        var tblDepartmentMaster = await _context.TblDepartmentMaster.FindAsync(id);

        if (tblDepartmentMaster == null)
        {
            return NotFound();
        }

        return tblDepartmentMaster;
    }

    // PUT: api/TblDepartments/5
    // To protect from overposting attacks, enable the specific properties you want to bind to, for
    // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
    [HttpPut("{id}")]
    public async Task<IActionResult> PutTblDepartmentMaster(int id, TblDepartmentMaster tblDepartmentMaster)
    {
        if (id != tblDepartmentMaster.DepartmentId)
        {
            return BadRequest();
        }

        _context.Entry(tblDepartmentMaster).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!TblDepartmentMasterExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/TblDepartments
    // To protect from overposting attacks, enable the specific properties you want to bind to, for
    // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
    [HttpPost]
    public async Task<ActionResult<TblDepartmentMaster>> PostTblDepartmentMaster(TblDepartmentMaster tblDepartmentMaster)
    {
        _context.TblDepartmentMaster.Add(tblDepartmentMaster);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetTblDepartmentMaster", new { id = tblDepartmentMaster.DepartmentId }, tblDepartmentMaster);
    }

    // DELETE: api/TblDepartments/5
    [HttpDelete("{id}")]
    public async Task<ActionResult<TblDepartmentMaster>> DeleteTblDepartmentMaster(int id)
    {
        var tblDepartmentMaster = await _context.TblDepartmentMaster.FindAsync(id);
        if (tblDepartmentMaster == null)
        {
            return NotFound();
        }

        _context.TblDepartmentMaster.Remove(tblDepartmentMaster);
        await _context.SaveChangesAsync();

        return tblDepartmentMaster;
    }

    private bool TblDepartmentMasterExists(int id)
    {
        return _context.TblDepartmentMaster.Any(e => e.DepartmentId == id);
    }
}
}

但是它触发了一个错误说

nvalidOperationException: Unable to resolve service for type 'SanApi.Models.ClassooContext' while attempting to activate 'SanApi.Controllers.TblDepartmentsController'.

自从它自动生成以来,我一直不知道错误在哪里。我对 Web API 很陌生。所以卡住了。

创建数据库上下文后,如:

public class ClassooContext : DbContext
{
    public ClassooContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }

    public DbSet<Course> Courses { get; set; }

}

您需要注册ClassooContext。 ASP.NET Core 默认实现依赖注入。服务(例如 EF 数据库上下文)在应用程序启动期间使用依赖注入进行注册。要将 ClassooContext 注册为服务,请打开 Startup.cs,并将突出显示的行添加到 ConfigureServices 方法:

services.AddDbContext<ClassooContext>(options =>
 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

然后打开 appsettings.json 文件并添加一个连接字符串,例如:

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true"
},

然后您可以注入控制器以使用 EF 上下文,如:

private readonly ClassooContext _context;

public TblDepartmentsController(ClassooContext context)
{
    _context = context;
}