【发布时间】:2011-06-15 17:32:12
【问题描述】:
我的 DTO(为演示目的而简化):
Item(映射到我的相关 ViewModel 的 DTO):
public class Item {
public Item() { }
public virtual Guid ID { get; set; }
public virtual ItemType ItemType { get; set; }
public virtual string Title { get; set; }
}
ItemType(由我的 Item 类引用):
public class ItemType {
public ItemType() { }
public virtual Guid ID { get; set; }
public virtual IList<Item> Items { get; set; }
public virtual string Name { get; set; }
}
我的 ViewModel(用于编辑我的 Item 类数据):
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);
}
}
我的 AutoMapper 映射代码:
Mapper.CreateMap<Item, ItemEditViewModel>()
.ForMember(dest => dest.ItemTypes, opt => opt.Ignore());
Mapper.CreateMap<ItemEditViewModel, Item>();
控制器代码(再次,为演示而简化):
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);
}
现在,发生了什么事:
在我的控制器中的 HttpPost Create 操作结果中,我使用 Automapper 将我的 ItemEditViewModel 映射到我的 Item DTO 类,在 SelectList 中选择的 ItemType ID 值不会绑定到 Item.ItemType.ID 属性。 Item.ItemType 属性为空。
我认为这是因为,因为我的 Item DTO 类中没有 ItemTypeID Guid 值,并且我没有为我的 Item DTO 中的同名属性创建新的 ItemType 类,所以 AutoMapper 无法存储 ItemType ID 值。
我认为这取决于我的 Automapper 映射配置。
我确定我忽略了一些简单的事情。
提前感谢您的任何建议!
【问题讨论】: