Whenever I try to change Department and Position objects of the Employee class they are not updating inside database on the Employee entity. For example, I want to change employee Position from junior (id - 1, name of the position - junior) to middle (id - 2, name of the position - middle). But, whenever I try to save this changes to the database they don't apply.
My Employee entity
public class Employee
{
public int EmployeeId { get; set; }
public string FullName { get; set; }
public Department Department { get; set; }
public EmployeePosition Position { get; set; }
public string Head { get; set; }
public double Salary { get; set; }
public Employee()
{
Department = new Department();
Position = new EmployeePosition();
}
}
EmployeePosition entity
public class EmployeePosition
{
public int Id { get; set; }
public string Name { get; set; }
}
My modify employee method in ViewModel
public void ModifyEmployee(int id)
{
Employee employee = employeeRepository.GetEmployee(id);
using (var context = new PowerCoEntity())
{
employee.Position = context.EmployeePositions.FirstOrDefault(d => d.Id == SelectedPositionId);
employee.Department = context.Deprtments.FirstOrDefault(d => d.DepartmentId == SelectedDepartmentId);
if (SelectedHeadId != null)
employee.Head = employeeRepository.GetHeadName(SelectedHeadId.Value);
else employee.Head = "";
}
employee.Salary = Employee.Salary;
employee.FullName = Employee.FullName;
employeeRepository.ModifyEmployee(employee);
}
Modify method in the context class
public void ModifyEmployee(Employee employee)
{
using (var context = new PowerCoEntity())
{
context.Entry(employee).State = EntityState.Modified;
context.SaveChanges();
}
}
UPDATE 1
I got it working by changing ModifyEmployee methods in the ViewModel and Context class. But I need to pass all the parameters through method now. How can I be able to use different contexts to modify object? Context class:
public void ModifyEmployee(int id, int selectedPositionId, int selectedDepartmentId, int? selectedHeadId, Employee employee)
{
using (var context = new PowerCoEntity())
{
Employee emp = context.Employees.FirstOrDefault(e=> e.EmployeeId == 32);
emp.Salary = employee.Salary;
emp.FullName = employee.FullName;
emp.Department = employee.Department;
emp.Position = context.EmployeePositions.FirstOrDefault(d => d.Id == selectedPositionId);
emp.Department = context.Deprtments.FirstOrDefault(d => d.DepartmentId == selectedDepartmentId);
if (selectedHeadId != null)
emp.Head = GetHeadName(selectedHeadId.Value);
else emp.Head = "";
emp.Salary = employee.Salary;
emp.FullName = employee.FullName;
context.Entry(emp).State = EntityState.Modified;
context.SaveChanges();
}
}
ViewModel:
public void ModifyEmployee(int id)
{
Employee employee = new Employee();
employee.Salary = Employee.Salary;
employee.FullName = Employee.FullName;
employeeRepository.ModifyEmployee(id, SelectedPositionId, SelectedDepartmentId, SelectedHeadId, employee);
}