Home > Software design >  InvalidOperationException: Unable to resolve service for type 'StudentWebApp.Models.StudentAppC
InvalidOperationException: Unable to resolve service for type 'StudentWebApp.Models.StudentAppC

Time:07-31

I am trying to make a site. I created pages such as adding and deleting ready with Controller. But I am getting an error on the pages.

ClassTablesController.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 StudentWebApp.Models;

namespace StudentWebApp.Controllers
{
    public class ClassTablesController : Controller
    {
        private readonly StudentAppContext _context;

        public ClassTablesController(StudentAppContext context)
        {
            _context = context;
        }

        // GET: ClassTables
        public async Task<IActionResult> ViewPage()
        {
              return _context.ClassTables != null ? 
                          View(await _context.ClassTables.ToListAsync()) :
                          Problem("Entity set 'StudentAppContext.ClassTables'  is null.");
        }

        // GET: ClassTables/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.ClassTables == null)
            {
                return NotFound();
            }

            var classTable = await _context.ClassTables
                .FirstOrDefaultAsync(m => m.Id == id);
            if (classTable == null)
            {
                return NotFound();
            }

            return View(classTable);
        }

        // GET: ClassTables/Create
        public IActionResult Create()
        {
            return View();
        }
        // POST: ClassTables/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,ClassName")] ClassTable classTable)
        {
            if (ModelState.IsValid)
            {
                _context.Add(classTable);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View("ClassTable/Create");
        }

        // GET: ClassTables/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.ClassTables == null)
            {
                return NotFound();
            }

            var classTable = await _context.ClassTables.FindAsync(id);
            if (classTable == null)
            {
                return NotFound();
            }
            return View(classTable);
        }

        // POST: ClassTables/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,ClassName")] ClassTable classTable)
        {
            if (id != classTable.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(classTable);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ClassTableExists(classTable.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(classTable);
        }

        // GET: ClassTables/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.ClassTables == null)
            {
                return NotFound();
            }

            var classTable = await _context.ClassTables
                .FirstOrDefaultAsync(m => m.Id == id);
            if (classTable == null)
            {
                return NotFound();
            }

            return View(classTable);
        }

        // POST: ClassTables/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.ClassTables == null)
            {
                return Problem("Entity set 'StudentAppContext.ClassTables'  is null.");
            }
            var classTable = await _context.ClassTables.FindAsync(id);
            if (classTable != null)
            {
                _context.ClassTables.Remove(classTable);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ClassTableExists(int id)
        {
          return (_context.ClassTables?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}

Shared/_layout.cshtml:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - Student Web App</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/StudentWebApp.styles.css" asp-append-version="true" />
</head>
<body>
    <header>
        <nav >
            <div >
                <a  asp-area="" asp-controller="Home" asp-action="Index">Student Web App</a>
                <button  type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span ></span>
                </button>
                <div >
                    <ul >
                        <li >
                            <a  href="Index">Home</a>
                        </li>
                        <li >
                            <a  href="Home/ManageClass">Manage Class</a>
                        </li>
                        <li >
                            <a  href="Home/ManageStudents">Manage Student</a>
                        </li>
                        <li >
                            <a  href="/ClassTables/Create">Create</a>
                        </li>
                        <li >
                            <a  href="/ClassTables/Delete">Delete</a>
                        </li>
                        <li >
                            <a  href="/ClassTables/Details">Details</a>
                        </li>
                        <li >
                            <a  href="/ClassTables/Edit">Edit</a>
                        </li>
                        <li >
                            <a  href="/ClassTables/ViewPage">View</a>
                        </li>
                        <li >
                            <a  href="Home/ManageStudents">Manage Student</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div >
        <main role="main" >
            @RenderBody()
        </main>
    </div>

    <footer >
        <div >
            &copy; 2022 - StudentWebApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

The error I get is:

enter image description here

CodePudding user response:

In short: the ServiceCollection is trying to resolve type StudentAppContext but it doesn't know how to. You need to register it with the ServiceCollection so it can be used via Dependency Injection. More reading here.

First, you're going to want to find where the ServiceCollection is being configured. You can usually find this in either Program.cs or Startup.cs (depending on how your app was created).

Assuming your StudentAppContext extends EntityFramework's DbContext, it would look something like this:

services.AddDbContext<StudentAppContext>(options => options.UseSqlServer(...));

But this of course is an oversimplification. It is assuming you're using Sql, and there is certainly more that can potentially go into it. More reading on this can be found here.

Or, if it's simply a service you created that doesn't extend DbContext, you'll want to define its lifetime, for example:

services.AddTransient<StudentAppContext>();
  • Related