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)

blog comments powered by Disqus

About the author

You have probably figured out by now that my name is Bryan Avery (if not, please refer to your browser's address field).  Technology is more than a career to me - it is both a hobby and a passion.  I'm an ASP.NET/C# Developer at heart...

Month List