A good practice in ASP.NET MVC can be to separate the model from the database and the model for presentation. In your case, we will have two models: EmployeeDTO and Employee.
public class EmployeeDTO { public int Id { get; set; } public string Name { get; set; } public int Salary { get; set; } } public class Employee { public int Id { get; set; } public string Name { get; set; } public int Salary { get; set; } public int AnnualSalary { get { return this.Salary * 12; } } }
After that, on your controller, you map EmployeeDTO to Employee (to read the action) and Employee to EmployeeDTO (to create / update actions). For example, the Read method:
public ActionResult Read(int id) { EmployeeDTO employeeDTO = db.Employee.Find(id); Employee employee = new Employee() { Id = employeeDTO.Id, Name = employeeDTO.Name, Salary = employeeDTO.Salary }; return View(employee); }
With this convention, you can implement DataAnnotations for EmployeeDTO, which does not automatically apply to Employee (like your view) and vice versa. In your case, you can add a new property that does not affect the database schema.
Hope this helps.
source share