Easy way to update models in your ASP.NET MVC business layer
Brad Wilson just mentioned that the MVC Futures library has a static ModelCopier class with a CopyModel(object from, object to) static method. It uses reflection to match properties with the same name and compatible types.
In short, instead of manually copying over properties as shown here:
public void Save(EmployeeViewModel employeeViewModel)
{
var employee = (from emp in dataContext.Employees
where emp.EmployeeID == employeeViewModel.EmployeeID
select emp).SingleOrDefault();
if (employee != null)
{
employee.Address = employeeViewModel.Address;
employee.Salary = employeeViewModel.Salary;
employee.Title = employeeViewModel.Title;
}
dataContext.SubmitChanges();
}
you do this:
public void Save(EmployeeViewModel employeeViewModel)
{
var employee = (from emp in dataContext.Employees
where emp.EmployeeID == employeeViewModel.EmployeeID
select emp).SingleOrDefault();
if (employee != null)
{
ModelCopier.CopyModel(employeeViewModel, employee);
}
dataContext.SubmitChanges();
}
Beautiful, isn’t it?