Question

I have a legacy table represented by the following model:

public class Employee
{
    [Key]
    [Column("employee_id")]
    public string EmployeeId { get; set; }

    [Column("first_name")]
    public string FirstName { get; set; }

    [Column("last_name")]
    public string LastName { get; set; }

    [Column("active")]
    public bool Active { get; set; }
}

I don't have a viewmodel for this class and it will only be used to populate SelectLists (via repository) in other viewmodels in my app. However, I want to create a property like so, to concatenate the first and last names for the SelectLists/dropdown:

    private string _EmployeeName;
    public string EmployeeName
    {
        get
        {
            return _EmployeeName;
        }
        set
        {
            _EmployeeName = this.FirstName + " " + this.LastName;
        }
    }

When I put the EmployeeName in my Employee model, I get an error that the column EmployeeName doesn't exist. Ok, makes sense because this is my model and their is no such column.

Here is an abbreviated example of one viewmodelthat uses the SelectList:

public class EquipmentViewModel
{
    [Display(Name = "Equipment ID:")]
    public string EquipmentId { get; set; }

    [Required(ErrorMessage = "Equipment name is required.")]
    [Display(Name = "Equipment Name:")]
    [MaxLength(128)]
    public string EquipmentName { get; set; }

    public SelectList EmployeeList { get; set; }
}

In my controller, I do this:

var emp = iEmployeeRepository.FindBy(x => x.Active == true).OrderBy(x => x.FirstName);
var equipmentViewModel = new EquipmentViewModel
{
    EquipmentId = e.EquipmentId,
    EquipmentName = e.EquipmentName,
    OriginatorEmployeeId = e.OriginatorEmployeeId,
    EmployeeList = new SelectList(emp, "EmployeeId", "FirstName"),
};
return View(equipmentViewModel);

Since I don't have a viewmodel for the Employee class, where can I put this EmployeeName property to replace FirstName? If someone could point me in the right direction I'd be grateful.

Was it helpful?

Solution

You don't need an EmployeeName property. Do this in your controller:

var emp = iEmployeeRepository.FindBy(x => x.Active == true)
                             .OrderBy(x => x.FirstName)
                             .Select(x => new { EmployeeId = x.EmployeeId, EmployeeName = x.FristName + " " + x.LastName });
var equipmentViewModel = new EquipmentViewModel
{
    EquipmentId = e.EquipmentId,
    EquipmentName = e.EquipmentName,
    OriginatorEmployeeId = e.OriginatorEmployeeId,
    EmployeeList = new SelectList(emp, "EmployeeId", "EmployeeName"),
};
return View(equipmentViewModel);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top