Easy way to update models in your ASP.NET MVC business layer
Posted
by rajbk
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by rajbk
Published on Thu, 01 Apr 2010 04:10:03 GMT
Indexed on
2010/04/01
4:13 UTC
Read the original article
Hit count: 627
Brad Wilson just mentioned there is a static class ModelCopier that has a static method CopyModel(object from, object to) in the MVC Futures library. 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 can use the method like so:
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();
}
© ASP.net Weblogs or respective owner