Dotnetpdf 4
Dotnetpdf 4
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.
1. *Install .NET Core SDK*: Make sure you have the .NET Core SDK installed on your machine
[here](https://dotnet.microsoft.com/download).
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
ApplicationUser.cs:
csharp
using Microsoft.AspNetCore.Identity;
ApplicationDbContext.cs:
csharp
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
EmployeeController.cs:
csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
// 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();
}
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();
}
// 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();
}
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));
}
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>
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();
});
}
`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);
[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