Using AutoMapper to map complex viewmodel back to model with collection property
I have EF an EF generated class of Person that has several properties. I also have a class Jobs with several properties. A person is related to multiple jobs and thus Jobs is a Collection property of person.
I have created a view model as such:
public class PersonViewModel
{
public Person Person{ get; set; }
public List<Job> Jobs{ get; set; }
}
From my view, I am posting an instance of PersonViewModel. I would like to use AutoMapper to map This viewmodel back to an instance of Person with its Jobs collection property filled with the list from the view model.
Can this be accomplished? So far I have tried:
Mapper.CreateMap<PersonViewModel, Person>();
with no luck...
EDIT:
OK, this does actually work. I discovered that I have a problem开发者_Python百科 elsewhere...
My Person object also has a one-many relationship with a PersonType table... PersonType becomes a navigation property of Person and auto mapper is trying to map this...this is where it fails...I am successfully passing a PersonTypeID to associate Person with person type. I had assumed this would be all I needed to do. How can I get around this issue...
EDIT 2: So basically my Person table in the DB has a PersonTypeID column(foreign key to PersonType table)...this gets mapped as a navigation property of Person as PersonType object...
From the form in my view, I have a dropdown list to choose person Type which passes PersonTypeID property back in the Person Object within the view model...
automapper seems to be looking for a value for the PersonType nav property of Person to map...I am getting an AutoMapper.AutoMapperMappingException
Error
Destination property: PersonType
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
Yes, this should work. If the Model and ViewModel share the same properties - be it a collection - they will be mapped by AutoMapper automatically but:
- They need be named the same
- If mapping is two-ways, map needs to be created two way as well, and I have found even if it is one-way, I had to create the mapboth ways
- If you have
Job
andJobViewModel
so the collections are of different types (but named the same way) just create a map for these as well.
My hunch is this should solve your issue: create maps two ways to see if it helps:
Mapper.CreateMap<PersonViewModel, Person>();
Mapper.CreateMap<Person, PersonViewModel>();
EDIT
If you have properties on your ViewModel and Model and they are of different type, AutoMapper would not know how to convert them. So one option is to ignore them:
Automapper: Ignore on condition of
Or you can use Custom mapping:
http://lostechies.com/jimmybogard/2009/05/06/automapper-feature-custom-type-converters/
Or try reverse to mapping:
Mapper.CreateMap<Person, PersonViewModel>().ReverseMap();
精彩评论