I am trying to run the Index page of Employees controller but once I play and run, it gives me this error as shown below,
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'ApplicationDbContext' while attempting to activate 'Employeeproject.Views.EmployeesController'.
Please find my Employee Model class
namespace Employeeproject.Models
{
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public int PhoneNo { get; set; }
}
}
The index function has been already written in the Employees controller. Please find it below,
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 Employeeproject.Models;
namespace Employeeproject.Views
{
public class EmployeesController : Controller
{
private readonly ApplicationDbContext _context;
public EmployeesController(ApplicationDbContext context)
{
_context = context;
}
// GET: Employees
public async Task<IActionResult> Index()
{
return View(await _context.Employee.ToListAsync());
}
}
}
Please find the Employees Db Context code below,
using Employeeproject.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Identity.Client;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Employeeproject.Models.Employee> Employee { get; set; } = default!;
// DbSets go here
}
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer("DefaultConnection");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
Please find the program.cs code below
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Employees}/{action=Index}/{id?}");
app.Run();
The appsetting.json code is mentioned below,
{
"ConnectionStrings": {
"DefaultConnection": "Server=user;",
"Server": "Server=User\\SQLEXPRESS;Database:Employees; User Id=xxxx;Password:xxxx; TrueServerCertificate=True"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Currently I would like to run the Employees Controller Index page. It seems like there is some issue on the connection string in appsettings.json. If I go to the properties of my Server in SQL Management studio, the name is only "User" there so I have given exactly right now in the connection string. The Migration has already been created with InitialMigrations.cs
you can create a new .Net 8 MVC application using VS 2022 and please select Authentication Type as Individual Account when you choose .Net version.
Then you will have a sample project using EF core to connection sql server. And you will also see builder.Services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(connectionString));
in Program.cs, this line injects DbContext.
In your error message we could see ApplicationDbContext
hasn't completed Dependency Injection. And that's why I say you need to add builder.Services.AddDbContext
. If you had extra errors, you can also compare your project with this sample app to get information like nuget packages and their version. The sample app integrates Asp.net Core default Identity.