I have error when I make web app with EF 6.0.
InvalidOperationException: Unable to resolve service for type 'WebbyMyself.Models.StudentManageEntities' while attempting to activate 'WebbyMyself.Controllers.BranchesController'.
It has Models/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; } } }
And 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()); } } }
And 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>
I use Code Generation in Visual Studio 2022.
I don't know how to fix, so pls help me.
I don't know how to describe so if you want more information pls tell me. Thank you so much.
You need to register your DbContext class with name "StudentManageEntities" like this on Program.cs file:
services.AddDbContext<StudentManageEntities>();
or like this:
services.AddDbContext<StudentManageEntities>(options =>
options.UseSqlServer(@"Your connection string"));