Auto-parameter matching problem: anti-aliasing from DTO to ViewModel works - doesn't work the other way around

My DTOs (simplified for demo purposes):

Element (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 (link to 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 element class data):

public class ItemEditViewModel {
    public ItemEditViewModel () { }
    public Guid ID { get; set; }
    public Guid ItemTypeID { get; set; }
    public string Title { get; set; }
    public SelectList ItemTypes { 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 happens:

In my HttpPost Create an action in my controller where I use Automapper to map my ItemEditViewModel to the DOT class of my item, the value of the ItemType selected in the SelectList is not bound to the Item.ItemType.ID property. The Item.ItemType property is null.

, , , ItemTypeID Guid Item DTO, ItemType Item DTO, AutoMapper ItemType ID.

, Automapper.

, - , .

!

+3
2

, , automapper Big Shape- > Smaller/Flat Shape, . .

+2

:

Mapper.CreateMap<ItemEditViewModel, Item>()
    .ForMember(dest => dest.ItemType, opt => opt.MapFrom(src =>
        {
            return new ItemType()
                {
                    ID = src.ItemTypeID
                }
        };
+1

All Articles