I need to have a view that displays Employee First and Last Name and the Employees associated Supervisor First and Last name.
I have 2 models they are as follow:
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
public int SupervisorID { get; set; }
public virtual ICollection<Supervisor> Supervisor { get; set; }
}
public class Supervisor
{
public int SupervisorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Department { get; set; }
public virtual Employee Employee { get; set; }
}
To display the needed data I have created another model:
public class EmployeeSupervisor
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
public string SupFirstName { get; set; }
public string SupLastName { get; set; }
public string SupPhone { get; set; }
public string SuoEmail { get; set; }
public string SupDepartment { get; set; }
}
and in the details action of a controller I do the following:
Employee employee = db.Employees.Find(id);
Supervisor supervisor = db.Supervisors.Find(employee.SupervisorID);
EmployeeSupervisor es = new EmployeeSupervisor
{
EmployeeID = employee.EmployeeID,
Department = employee.Department,
FirstName = employee.FirstName,
LastName = employee.LastName,
SupFirstName = supervisor.FirstName,
SupLastName = supervisor.LastName,
SuoEmail = supervisor.Email,
SupPhone = supervisor.Phone,
SupDepartment = supervisor.Department
};
return View(es);
Then in the view I have
@model TimeOffV3.Models.EmployeeSupervisor
and then lastly I do the following in the view
@Html.DisplayFor(model => model.FirstName)
@Html.DisplayFor(model => model.LastName)
@Html.DisplayFor(model => model.SupFirstName)
@Html.DisplayFor(model => model.SupLastName)
When I accomplish this task as described above with the EmployeeSupervisor model class, entity framework creates a corresponding table for EmployeeSupervisor in the database (as expected). This leads me to believe I'm doing it the wrong way as I can't imagine everytime I want to display data from 2 different models I need to create a new corresponding model and table.
Is the way I accomplished this correct? Should I be able to access the supervisor information using the navigation property defined in the Employee class? Can I pass in multiple models so I don't have to create a model containing the info from 2 separate models?