【问题标题】:Scafolded controller class trigger invalidoperationexception脚手架控制器类触发无效操作异常
【发布时间】:2020-05-05 15:54:19
【问题描述】:

我正在尝试学习一些 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:无法解析服务类型 尝试激活时出现“SanApi.Models.ClassooContext” 'SanApi.Controllers.TblDepartmentsController'。

自从它自动生成以及错误在哪里以来,我还没有得到任何想法。我对 Web API 很陌生。所以卡住了。

【问题讨论】:

    标签: asp.net-core asp.net-web-api2 asp.net-core-webapi


    【解决方案1】:

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

    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;
    }
    

    【讨论】:

    • 你是个了不起的人.. 但只是想为什么 VS 不自动添加它,因为它对自动生成的控制器工作很重要/必须具有
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    相关资源
    最近更新 更多