Easy way to update models in your ASP.NET MVC business layer - Raj Kaimal

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?

Published Wednesday, March 31, 2010 11:10 PM by rajbk
Filed under: , , ,

Comments

# re: Easy way to update models in your ASP.NET MVC business layer

Really nice. Thanks for the update Raj.

Arun

Thursday, April 1, 2010 12:24 AM by Arun Mahendrakar

# re: Easy way to update models in your ASP.NET MVC business layer

AutoMapper (automapper.codeplex.com) does exactly this kind of stuff :)

Thursday, April 1, 2010 3:50 PM by vmr_lethal

# re: Easy way to update models in your ASP.NET MVC business layer

Hi,

Is there any way to control which properties are getting copied over.

Thank,s

Thani

Saturday, April 17, 2010 9:07 AM by Thanigainathan

# re: Easy way to update models in your ASP.NET MVC business layer

Very nice!

Saturday, April 17, 2010 9:35 PM by azamsharp