MVC 2 makes it easier to copy models

With MVC 2 now released, I have found a nice little feature for updating models.

The normal practice is to use, a mapping technique like this

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();
}

But now we can use the ModelCopier, which uses reflection to transpose the model

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();
}

So, you’ve tried it out, but you can’t find ModelCopier?  That is because is part of MVC 2 futures, what a tease 😉

I have however created this extended version of an Object Copier, which also copies objects inside of the object.

ObjectCopier.zip (50.83 kb)