При обработке запроса произошло необработанное исключение.
InvalidOperationException: невозможно разрешить службу для типа «ApplicationDbContext» при попытке активировать «Employeeproject.Views.EmployeesController».
Найдите мой класс модели сотрудника
Код: Выделить всё
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; }
}
}
Код: Выделить всё
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 Index()
{
return View(await _context.Employee.ToListAsync());
}
}
}
Код: Выделить всё
using Employeeproject.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Identity.Client;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet Employee { get; set; } = default!;
// DbSets go here
}
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer("DefaultConnection");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
Код: Выделить всё
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();
Код: Выделить всё
{
"ConnectionStrings": {
"DefaultConnection": "Server=user;",
"Server": "Server=User\\SQLEXPRESS;Database:Employees; User Id=xxxx;Password:xxxx; TrueServerCertificate=True"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... tiondbcont