asp.net-mvc - Automapper 映射问题 : flattening from DTO to ViewModel works - doesn't work the other way around

标签 asp.net-mvc automapper

我的 DTO(为演示目的而简化):

项目(映射到我有问题的 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>();

Controller 代码(再次简化演示):

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);
}

现在,这是正在发生的事情:

在我的 Controller 中的 HttpPost Create 操作结果中,我使用 Automapper 将 ItemEditViewModel 映射到 Item DTO 类,在 SelectList 中选择的 ItemType ID 值未绑定(bind)到 Item.ItemType.ID 属性。 Item.ItemType 属性为空。

我认为这是因为,因为我的 Item DTO 类中没有 ItemTypeID Guid 值,而且我还没有为我的 Item DTO 中的同名属性创建新的 ItemType 类,所以 AutoMapper 无法存储 ItemType ID 值。

我认为这归结为我的 Automapper 映射配置。

我确信我忽略了一些简单的事情。

提前感谢您的任何建议!

最佳答案

很确定这是因为 automapper 被设计为大形状 -> 较小/平面形状映射工具,而不是相反。这只是不受支持。

关于asp.net-mvc - Automapper 映射问题 : flattening from DTO to ViewModel works - doesn't work the other way around,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6361777/

相关文章:

asp.net-mvc - View.Title == ViewData ["Title"]

c# - AutoMapper 不适用于容器类

c# - AutoMapper AutoMapper.AutoMapperMappingException : Error mapping types

automapper - AutoMapper字典拼合

c# - 自动映射器 : how to eleminate repetitive mapping?

dependency-injection - 在 ASP.NET Core 中将依赖项注入(inject)到 Automapper TypeConverter

c# - ASP.NET MVC DropDownList NullReferenceException

c# - 强类型 T4MVC Action /ActionLink

c# - 使用C#在浏览器中打开word文件

c# - mvc 中创建表单的默认值