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 01, 2010 12:24 AM by Arun Mahendrakar

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

True..!!

Thursday, April 01, 2010 1:03 AM by krunal

# Securing an ASP.NET MVC 2 Application

This post attempts to look at some of the methods that can be used to secure an ASP.NET MVC 2 Application

Thursday, April 01, 2010 2:39 AM by Raj Kaimal

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

If you need more features than just plain prop-to-prop copying, check out AutoMapper (http://automapper.codeplex.com). It has that feature plus a ton more of awesomeness.

Thursday, April 01, 2010 11:06 AM by Javier Lozano

# 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 01, 2010 3:50 PM by vmr_lethal

# CopyModel. :D http://weblogs.asp.net/rajbk/archive/2010/03/31/easy-way-to-update-models-in-your-asp-net-mvc-business-layer.aspx #apsnetmvc

CopyModel. :D http://weblogs. asp.net /rajbk/archive/2010/03/31/easy-way-to-update-models-in-your-asp

Thursday, April 01, 2010 7:02 PM by Twitter Mirror

# 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