I have a view for editing a specific project. Here is what I do for preparing a view model for this view:
- Retrieve project info
- Prepare a new view model object anp map my project into it.
- Prepare a TechnologyString by calling a function to fill it.
-
Showing the view.
public ActionResult Edit(string slug) { // 1 Project project = m_ProjectBusiness.GetProject(slug); // 2 ProjectEditViewModel viewModel = new ProjectEditViewModel { ProjectToEdit = Mapper.Map<Project, ProjectFullViewModel>(project) }; // 3 viewModel.ProjectToEdit.TechnologyString = m_ProjectBusiness.ListTechnologies(project); // 4 return View(viewModel); }
As you can see for point 3, I fill in a string (TechnologyString) located in my view model, under my object ProjectToEdit. I would like to know if it is possible to do this operation directly (and automatically) when the mapping occurs?
Thanks.
EDIT
I found a solution based on mapping. Here it is:
Mapper.CreateMap<Project, ProjectFullViewModel>()
.ForMember(dest => dest.TechnologyString,
opt => opt.MapFrom(src => String.Join(" ", src.Technologies.Select(x => x.Name))));
So, I retrieve every technologies attached to my project and create a string with all items separated by a space.
Readers: Please note that Darin’s solution below works in case of Technologies are not part of my domain model. But in this case it is.
This is not something that should be handled at your mapping level. You could use a service layer in which you will define an aggregate root for the project and the technology:
and then have a method in your service layer that will return this aggregate root:
and then you could directly map between the aggregate root that will be returned by your service layer and the view model, like so: