Reputation: 21
I get an error
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type Employees.Models.EmployeesContext
while attempting to activate Employees.Areas.Admin.Controllers.DepartmentsController
.
Here is my code:(Database first)
Model:(Departments.cs
)
using System;
using System.Collections.Generic;
namespace Employees.Models
{
public partial class Departments
{
public Departments()
{
EmployeeDepartments = new HashSet<EmployeeDepartments>();
}
public string DepartmentCode { get; set; }
public string Name { get; set; }
public DateTime? CreatedOn { get; set; }
public ICollection<EmployeeDepartments> EmployeeDepartments { get; set; }
}
}
Model(EmployeesContext.cs
)
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Employees.Models
{
public partial class EmployeesContext : DbContext
{
public EmployeesContext()
{
}
public EmployeesContext(DbContextOptions<EmployeesContext> options)
: base(options)
{
}
public virtual DbSet<Departments> Departments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Departments>(entity =>
{
entity.HasKey(e => e.DepartmentCode);
entity.Property(e => e.DepartmentCode)
.HasMaxLength(10)
.IsUnicode(false)
.ValueGeneratedNever();
entity.Property(e => e.CreatedOn).HasColumnType("datetime");
entity.Property(e => e.Name).HasMaxLength(100);
});
Controller:(DepartmentsController
)
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 Employees.Models;
namespace Employees.Areas.Admin.Controllers
{
[Area("Admin")]
public class DepartmentsController : Controller
{
private readonly EmployeesContext _context;
public DepartmentsController(EmployeesContext context)
{
_context = context;
}
// GET: Admin/Departments
public async Task<IActionResult> Index()
{
return View(await _context.Departments.ToListAsync());
}
// GET: Admin/Departments/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return NotFound();
}
var departments = await _context.Departments
.FirstOrDefaultAsync(m => m.DepartmentCode == id);
if (departments == null)
{
return NotFound();
}
return View(departments);
}
// GET: Admin/Departments/Create
public IActionResult Create()
{
return View();
}
// POST: Admin/Departments/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("DepartmentCode,Name,CreatedOn")] Departments departments)
{
if (ModelState.IsValid)
{
_context.Add(departments);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(departments);
}
// GET: Admin/Departments/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}
var departments = await _context.Departments.FindAsync(id);
if (departments == null)
{
return NotFound();
}
return View(departments);
}
// POST: Admin/Departments/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("DepartmentCode,Name,CreatedOn")] Departments departments)
{
if (id != departments.DepartmentCode)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(departments);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!DepartmentsExists(departments.DepartmentCode))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(departments);
}
// GET: Admin/Departments/Delete/5
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
var departments = await _context.Departments
.FirstOrDefaultAsync(m => m.DepartmentCode == id);
if (departments == null)
{
return NotFound();
}
return View(departments);
}
// POST: Admin/Departments/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
var departments = await _context.Departments.FindAsync(id);
_context.Departments.Remove(departments);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool DepartmentsExists(string id)
{
return _context.Departments.Any(e => e.DepartmentCode == id);
}
}
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Employees.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Employees
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
{
var connectionString = @"DefaultConnection";
services.AddDbContext<EmployeesContext>(options => options.UseSqlServer(connectionString));
}
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area=Employee}/{controller=Home}/{action=Index}/{id?}"
);
});
}
}
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=PHONG-PC\\SQLEXPRESS;Database=Employees;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Employees
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Please help me.
Upvotes: 2
Views: 10892
Reputation: 1658
You need to Register and configure your context
in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
var connectionString = @"Server=.\\SQLExpress;Database=Employees;Trusted_Connection=True;";
services.AddDbContext<EmployeesContext>(options => options.UseSqlServer(connectionString));
}
According to Docs
Registers the given context as a service in the Microsoft.Extensions.DependencyInjection.IServiceCollection. You use this method when using dependency injection in your application.
And delete your OnConfiguration
method
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=.\\SQLExpress;Database=Employees;Trusted_Connection=True;");
}
}
If you use OnConfiguration
in your DbContext
then you can simply create your Context
instance without passing the DbContextOptionsBuilder
.
For example:
using (var context = new EmployeeContext())
{
// do stuff
}
According to DOCS
An application can simply instantiate such a context without passing anything to its constructor
Upvotes: 1
Reputation: 7610
In Startup.ConfigureServices
, you need register your context like this :
services.AddDbContext<EmployeesContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
More information :
https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext
Upvotes: 0