employeemanagementsystem
Tuesday, 9 July 2024 2:44 PM
Let's dive into a more advanced practical example: creating a multi-tier ASP.NET Core MVC a
database, Entity Framework Core for data access, and dependency injection for better maint
simple "Employee Management System" that includes features like authentication, role-base
testing.
### Step 1: Set Up the Project
1. *Install .NET Core SDK*: Make sure you have the .NET Core SDK installed on your machine
[here](https://dotnet.microsoft.com/download).
2. *Create a New ASP.NET Core MVC Project*:
bash
dotnet new mvc -o EmployeeManagement
cd EmployeeManagement
3. *Add Required Packages*:
bash
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package Microsoft.NET.Test.Sdk
### Step 2: Set Up the Database with Entity Framework Core
1. *Create Models*:
Create a Models folder and add Employee.cs and ApplicationUser.cs files.
Employee.cs:
csharp
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
application with a SQL Server
tainability. We'll build a
ed access control, and unit
e. You can download it from
Employee.cs:
csharp
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public DateTime HireDate { get; set; }
}
ApplicationUser.cs:
csharp
using Microsoft.AspNetCore.Identity;
public class ApplicationUser : IdentityUser
{
// Additional properties can be added here
}
2. *Create the ApplicationDbContext*:
Create a Data folder and add ApplicationDbContext.cs.
ApplicationDbContext.cs:
csharp
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Employee> Employees { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
}
}
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
}
}
3. *Configure the Connection String*:
In appsettings.json, add the connection string for the SQL Server database.
json
"ConnectionStrings": {
"DefaultConnection":
"Server=(localdb)\\mssqllocaldb;Database=EmployeeDb;Trusted_Connection=True;Multiple
}
4. *Configure Services and Middleware*:
In Startup.cs, configure the services to use Entity Framework Core and Identity.
csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
### Step 3: Create Controllers and Views
1. *Create the EmployeeController*:
Create a Controllers folder and add EmployeeController.cs.
EmployeeController.cs:
csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
public class EmployeeController : Controller
{
private readonly ApplicationDbContext _context;
eActiveResultSets=true"
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
public class EmployeeController : Controller
{
private readonly ApplicationDbContext _context;
public EmployeeController(ApplicationDbContext context)
{
_context = context;
}
// GET: Employee
public async Task<IActionResult> Index()
{
return View(await _context.Employees.ToListAsync());
}
// GET: Employee/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees
.FirstOrDefaultAsync(m => m.Id == id);
if (employee == null)
{
return NotFound();
}
return View(employee);
}
// GET: Employee/Create
public IActionResult Create()
{
return View();
}
// POST: Employee/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Department,HireDate")] Emplo
{
oyee employee)
// POST: Employee/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Department,HireDate")] Emplo
{
if (ModelState.IsValid)
{
_context.Add(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(employee);
}
// GET: Employee/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees.FindAsync(id);
if (employee == null)
{
return NotFound();
}
return View(employee);
}
// POST: Employee/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Department,HireDate")] Em
{
if (id != employee.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(employee);
await _context.SaveChangesAsync();
oyee employee)
mployee employee)
{
if (id != employee.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(employee);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(employee.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(employee);
}
// GET: Employee/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees
.FirstOrDefaultAsync(m => m.Id == id);
if (employee == null)
{
return NotFound();
}
return View(employee);
}
return NotFound();
}
return View(employee);
}
// POST: Employee/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var employee = await _context.Employees.FindAsync(id);
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool EmployeeExists(int id)
{
return _context.Employees.Any(e => e.Id == id);
}
}
2. *Create the Views*:
Create views for the Employee entity under the Views/Employee folder:
Index.cshtml, Details.cshtml, Create.cshtml, Edit.cshtml, and Delete.cshtml. Here's
a simple example of Index.cshtml:
Index.cshtml:
html
@model IEnumerable<EmployeeManagement.Models.Employee>
<h2>Employee List</h2>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Hire Date</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
<td>@Html.DisplayFor(modelItem => item.Department)</td>
<td>@Html.DisplayFor(modelItem => item.HireDate)</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>
<a asp-action="Create">Create New</a>
### Step 4: Add Authentication and Authorization
1. *Enable Authentication*:
In Startup.cs, configure the app to use authentication and authorization.
csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
2. *Create Account and Manage Roles*:
Implement account creation and role management for users. This involves
creating views and controllers for registration, login, and role management.
### Step 5: Add Unit Tests
1. *Create a Test Project*:
```bash
dotnet
new xunit -o EmployeeManagement.Tests
cd EmployeeManagement.Tests
dotnet add reference ../EmployeeManagement/EmployeeManagement.csproj
2. **Add Unit Tests**:
Create unit tests for the `EmployeeController` in the test project.
`EmployeeControllerTests.cs`:
csharp
public class EmployeeControllerTests
{
private readonly EmployeeController _controller;
private readonly ApplicationDbContext _context;
public EmployeeControllerTests()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.Options;
public EmployeeControllerTests()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.Options;
_context = new ApplicationDbContext(options);
_controller = new EmployeeController(_context);
}
[Fact]
public async Task Index_ReturnsViewResult_WithListOfEmployees()
{
// Arrange
_context.Employees.Add(new Employee { Name = "Test Employee",
Department = "HR", HireDate = DateTime.Now });
_context.SaveChanges();
// Act
var result = await _controller.Index();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<IEnumerable<Employee>>
(viewResult.ViewData.Model);
Assert.Single(model);
}
}
```
### Conclusion
This advanced practical example covers setting up an ASP.NET Core MVC
application with Entity Framework Core, authentication, role-based access control,
and unit testing. You can further extend this application by adding more features
such as email notifications, file uploads, or integrating with external APIs.