如何使用AutoMapper将destionation对象与源对象中的子对象映射? [英] How to use AutoMapper to map destionation object with a child object in the source object?

查看:978
本文介绍了如何使用AutoMapper将destionation对象与源对象中的子对象映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的源和目标对象:

I have the source and destination objects like this:

class ProductWithCategories // Source class
{
    public Product Product { get; set; } // Product is an EF entity class
    public IEnumerable<Category> Categories { get; set; }
}

class ProductViewModel // Dest class
{
    public int Id { get; set; }
    // Other properties with the same name as Product class

    public IEnumerable<CategoryViewModel> Categories { get; set; }
}

所以,我的需要是映射 source.Product into dest ,然后 source.Categories into dest.Categories 。是否可以使用AutoMapper?

So, my need is to map the values of source.Product into dest, and then source.Categories into dest.Categories. Is it possible with AutoMapper?

我已经尝试了这一点,当失败时我并不感到惊讶:

I have tried this and I was not surprised when it failed:

        config.CreateMap<ProductWithCategories, ProductViewModel>()
            .ForMember(q => q, option => option.MapFrom(q => q.Product))
            .ForMember(q => q.Categories, option => option.MapFrom(q => q.Categories));

这是我收到的例外:


[AutoMapperConfigurationException:成员的自定义配置是
仅对类型上的顶级个人成员支持。]

[AutoMapperConfigurationException: Custom configuration for members is only supported for top-level individual members on a type.]


推荐答案

经过与OP的讨论之后,他的主要需求是将源对象内的子/嵌套对象快速映射到展平的目标对象。他不想为目的地的每个物业写一个地图。

After some discussion with OP, it turns out his main need is to quickly map a child/nested object inside the source object to the flattened destination object. He does not want to write a mapping for every property of the destination.

这是一种实现这一点的方法:

Here is a way to achieve this:


  • 定义映射产品 - > ProductViewModel 用于展平产品的成员

  • 定义映射类别 CategoryViewModel

  • 定义映射类别的映射 ProductWithCategories - > ProductViewModel ,然后在映射,映射产品

  • Define a mapping Product -> ProductViewModel used to flatten the members of Product
  • Define a mapping Category to CategoryViewModel
  • Define a mapping ProductWithCategories -> ProductViewModel that maps the categories, and then in the aftermap, map the Product:

config.CreateMap< ProductWithCategories,ProductViewModel>()
.ForMember(q => q.Id,option => option.Ignore())//在AfterMap
.ForMember(q => q.Categories,option =>选项)中展平。 MapFrom(q => q.Categories))
.AfterMap((src,dst)=> Mapper.Map(src.Product,dst));

这篇关于如何使用AutoMapper将destionation对象与源对象中的子对象映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆