Created
October 27, 2023 04:03
-
-
Save abhishekluv/8d6938667bc85208a7823df47dc9b5e2 to your computer and use it in GitHub Desktop.
EF Core Loading Related Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using AdvancedEFCore.Models; | |
using AdvancedEFCore.ViewModels; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.AspNetCore.Mvc.Rendering; | |
using Microsoft.EntityFrameworkCore; | |
using Microsoft.Extensions.Caching.Distributed; | |
using System.Text.Json; | |
using System.Text.Json.Serialization; | |
namespace AdvancedEFCore.Controllers | |
{ | |
public class EmployeesController : Controller | |
{ | |
private readonly MyApplicationContext _context; | |
private readonly IDistributedCache _distributedCache; | |
private readonly ILogger<EmployeesController> _logger; | |
public EmployeesController(MyApplicationContext context, IDistributedCache distributedCache, ILogger<EmployeesController> logger) | |
{ | |
_context = context; | |
_distributedCache = distributedCache; | |
_logger = logger; | |
} | |
[HttpGet] | |
public IActionResult Index() | |
{ | |
//Lazy Loading | |
var employees = _context.Employees.ToList(); | |
return View(employees); | |
} | |
[HttpGet] | |
public IActionResult Create() | |
{ | |
ViewBag.Departments = GetDepartments(); | |
ViewBag.Skills = GetSkills(); | |
return View(); | |
} | |
[HttpPost] | |
public IActionResult Create(EmployeesViewModel viewModel) | |
{ | |
if (ModelState.IsValid) | |
{ | |
Employee employe = new Employee(); | |
employe.FirstName = viewModel.FirstName; | |
employe.LastName = viewModel.LastName; | |
employe.JoinedDate = viewModel.JoinedDate; | |
employe.Salary = viewModel.Salary; | |
employe.DepId = viewModel.DepartmentId; | |
EmployeeProfile profile = new() | |
{ | |
Email = viewModel.Profile.Email, | |
Phone = viewModel.Profile.Phone, | |
EmployeeId = employe.Id | |
}; | |
employe.Profile = profile; | |
foreach (var skillId in viewModel.SkillIds) | |
{ | |
var skill = _context.Skills.Where(x => x.Id == skillId).FirstOrDefault(); | |
employe.Skills.Add(skill); | |
} | |
_context.Employees.Add(employe); | |
_context.SaveChanges(); | |
_distributedCache.Remove("Employees"); | |
return RedirectToAction("Index"); | |
} | |
ViewBag.Departments = GetDepartments(); | |
ViewBag.Skills = GetSkills(); | |
return View(viewModel); | |
} | |
[HttpGet] | |
public IActionResult Edit(int id) | |
{ | |
var employee = _context.Employees | |
.Include(x => x.Profile) | |
.Include(x => x.Department) | |
.Include(x => x.Skills) | |
.FirstOrDefault(x => x.Id == id); | |
EmployeesViewModel viewModel = new EmployeesViewModel(); | |
viewModel.FirstName = employee.FirstName; | |
viewModel.LastName = employee.LastName; | |
viewModel.Salary = employee.Salary; | |
viewModel.JoinedDate = employee.JoinedDate; | |
viewModel.DepartmentId = employee.DepId; | |
viewModel.Profile = employee.Profile; | |
viewModel.Version = employee.Version; | |
viewModel.SkillIds = employee.Skills.Select(x => x.Id).ToArray(); | |
ViewBag.Departments = GetDepartments(); | |
ViewBag.Skills = GetSkills(); | |
return View(viewModel); | |
} | |
[HttpPost] | |
public IActionResult Edit(EmployeesViewModel viewModel) | |
{ | |
if (ModelState.IsValid) | |
{ | |
var employee = _context.Employees | |
.Include(x => x.Profile) | |
.Include(x => x.Department) | |
.Include(x => x.Skills) | |
.FirstOrDefault(x => x.Id == viewModel.Id); | |
employee.FirstName = viewModel.FirstName; | |
employee.LastName = viewModel.LastName; | |
employee.JoinedDate = viewModel.JoinedDate; | |
employee.DepId = viewModel.DepartmentId; | |
employee.Salary = viewModel.Salary; | |
employee.Profile.EmployeeId = employee.Id; | |
employee.Profile.Phone = viewModel.Profile.Phone; | |
employee.Profile.Email = viewModel.Profile.Email; | |
employee.Skills.Clear(); | |
foreach (var skillId in viewModel.SkillIds) | |
{ | |
var skill = _context.Skills.Where(x => x.Id == skillId).FirstOrDefault(); | |
employee.Skills.Add(skill); | |
} | |
_context.Employees.Update(employee); | |
_context.SaveChanges(); | |
return RedirectToAction("Index"); | |
} | |
return View(viewModel); | |
} | |
[HttpGet] | |
public IActionResult Delete(int id) | |
{ | |
var employee = _context.Employees.FirstOrDefault(x => x.Id == id); | |
return View(employee); | |
} | |
[HttpPost] | |
[ActionName("Delete")] | |
public IActionResult DeletePost(int id) | |
{ | |
var employee = _context.Employees.FirstOrDefault(x => x.Id == id); | |
_context.Employees.Remove(employee); | |
_context.SaveChanges(); | |
return RedirectToAction("Index"); | |
} | |
private List<SelectListItem> GetSkills() | |
{ | |
var skills = _context.Skills.ToList(); | |
var dropDown = new List<SelectListItem>(); | |
foreach (var skill in skills) | |
{ | |
dropDown.Add(new SelectListItem { Value = skill.Id.ToString(), Text = skill.Title }); | |
} | |
return dropDown; | |
} | |
//List<SelectListItem> | |
private List<SelectListItem> GetDepartments() | |
{ | |
var departments = _context.Departments.ToList(); | |
var dropDown = new List<SelectListItem>(); | |
foreach (var department in departments) | |
{ | |
dropDown.Add(new SelectListItem { Value = department.Id.ToString(), Text = department.Name }); | |
} | |
return dropDown; | |
} | |
[HttpGet] | |
public IActionResult IndexEager() | |
{ | |
var cachedEmpsJson = _distributedCache.GetString("Employees"); | |
var jsonOptions = new JsonSerializerOptions(); | |
jsonOptions.ReferenceHandler = ReferenceHandler.Preserve; | |
jsonOptions.WriteIndented = true; | |
if (cachedEmpsJson == null) | |
{ | |
_logger.LogInformation("Cached Missed"); | |
var employees = _context.Employees | |
.Include(x => x.Profile) | |
.Include(x => x.Department) | |
.Include(x => x.Skills) | |
.AsSingleQuery() | |
.AsNoTracking() | |
.ToList(); | |
var empsJson = JsonSerializer.Serialize(employees, jsonOptions); | |
_distributedCache.SetString("Employees", empsJson); | |
return View(employees); | |
} | |
_logger.LogInformation("Reading from Cache"); | |
var cachedEmployees = JsonSerializer.Deserialize<List<Employee>>(cachedEmpsJson, jsonOptions); | |
return View(cachedEmployees); | |
} | |
[HttpGet] | |
public IActionResult IndexExplicit() | |
{ | |
var employees = _context.Employees.ToList(); | |
foreach (var employee in employees) | |
{ | |
_context.Entry(employee).Collection(x => x.Skills).Load(); | |
_context.Entry(employee).Reference(x => x.Department).Load(); | |
_context.Entry(employee).Reference(x => x.Profile).Load(); | |
} | |
return View(employees); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment