My DTOs (simplified for demonstration purposes):
Item (the DTO mapped to my ViewModel in question):
public class Item {
public Item() { }
public virtual Guid ID { get; set; }
public virtual ItemType ItemType { get; set; }
public virtual string Title { get; set; }
}
ItemType (referenced by my Item class):
public class ItemType {
public ItemType() { }
public virtual Guid ID { get; set; }
public virtual IList<Item> Items { get; set; }
public virtual string Name { get; set; }
}
My ViewModel (for editing my Item class data):
public class ItemEditViewModel {
public ItemEditViewModel () { }
public Guid ID { get; set; }
public Guid ItemTypeID { get; set; }
public string Title { get; set; }
public SelectList ItemTy开发者_开发百科pes { get; set; }
public IEnumerable<ItemType> ItemTypeEntities { get; set; }
public BuildItemTypesSelectList(Guid? itemTypeID)
{
ItemTypes = new SelectList(ItemTypeEntities, "ID", "Name", itemTypeID);
}
}
My AutoMapper mapping code:
Mapper.CreateMap<Item, ItemEditViewModel>()
.ForMember(dest => dest.ItemTypes, opt => opt.Ignore());
Mapper.CreateMap<ItemEditViewModel, Item>();
Controller code (again, simplified for demonstration):
public ActionResult Create()
{
var itemVM = new ItemEditViewModel();
// Populates the ItemTypeEntities and ItemTypes properties in the ViewModel:
PopulateEditViewModelWithItemTypes(itemVM, null);
return View(itemVM);
}
[HttpPost]
public ActionResult Create(ItemEditViewModel itemVM)
{
if (ModelState.IsValid) {
Item newItem = new Item();
AutoMapper.Mapper.Map(itemVM, newItem);
newItem.ID = Guid.NewGuid();
...
// Validation and saving code here...
...
return RedirectToAction("Index");
}
PopulateEditViewModelWithItemTypes(itemVM, null);
return View(itemVM);
}
Now, here's what's happening:
Within my HttpPost Create action result in my controller where I use Automapper to map my ItemEditViewModel to my Item DTO class, the ItemType ID value selected in the SelectList doesn't bind to the Item.ItemType.ID property. The Item.ItemType property is null.
I assume this is because, since I don't have an ItemTypeID Guid value in my Item DTO class, and I haven't created a new ItemType class for the property of the same name in my Item DTO, AutoMapper is unable to store the ItemType ID value.
I think it comes down to my Automapper mapping configuration.
I'm sure it's something simple that I'm overlooking.
Thanks in advance for any advice!
Pretty sure this is because automapper was designed as a Big Shape-> Smaller/Flat Shape mapping tool, not the other way around. This just isn't supported.
You should be able to say:
Mapper.CreateMap<ItemEditViewModel, Item>()
.ForMember(dest => dest.ItemType, opt => opt.MapFrom(src =>
{
return new ItemType()
{
ID = src.ItemTypeID
}
};
精彩评论