using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Scheduling.Domain.Abstact;
using Scheduling.Domain.Entities;
using Scheduling.WebUI.Models;
namespace Scheduling.WebUI.Controllers
{
public class EmployeesController : Controller
{
private IDbContext context;
public int pageSize = 10;
public EmployeesController(IDbContext ctx)
{
context = ctx;
}
public ViewResult List(int page = 1)
{
ViewBag.Counter = (page - 1) * pageSize + 1;
EmployeeListViewModel model = new EmployeeListViewModel()
{
Employees = (from e in context.Employee
join s in context.Staff on new { EmployeeId = e.Id } equals new { s.EmployeeId } into s_join
from s in s_join.DefaultIfEmpty()
join d in context.Department on new { s.DepartmentId } equals new { DepartmentId = d.Id }
into d_join
from d in d_join.DefaultIfEmpty()
where
d.Id == 3 &&
d.CompanyId == 1
select e)
.OrderBy(e => e.Id)
.Skip((page - 1) * pageSize)
.Take(pageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = pageSize,
TotalItems = (from e in context.Employee
join s in context.Staff on new { EmployeeId = e.Id } equals new { s.EmployeeId } into s_join
from s in s_join.DefaultIfEmpty()
join d in context.Department on new { s.DepartmentId } equals new { DepartmentId = d.Id }
into d_join
from d in d_join.DefaultIfEmpty()
where
d.Id == 3 &&
d.CompanyId == 1
select e).Count()
}
};
return View(model);
}
public ViewResult Edit(int id)
{
Employee emp = context.Employee.Find(id);
return View(emp);
}
[HttpPost]
public ActionResult Edit(Employee emp)
{
if (ModelState.IsValid)
{
if (emp.Id != 0)
{
Employee dbEntry = context.Employee.Find(emp.Id);
if (dbEntry != null)
{
PropertyInfo[] properties = typeof (Employee).GetProperties();
foreach (var property in properties)
{
if (property.Name != "Id" && property.Name != "Staff")
{
property.SetValue(dbEntry, property.GetValue(emp));
}
}
}
}
else if (emp.Id == 0)
{
emp.Staff.Add(new Staff()
{
PostId = 2,
DepartmentId = 3
});
context.Employee.Add(emp);
}
context.SaveChanges();
return RedirectToAction("List");
}
return View(emp);
}
[HttpPost]
public RedirectToRouteResult Delete(int id)
{
Employee dbEntry = context.Employee.Find(id);
if (dbEntry != null)
{
context.Employee.Remove(dbEntry);
context.SaveChanges();
}
return RedirectToAction("List");
}
public ViewResult Create()
{
return View("Edit", new Employee());
}
}
}