c# - 如何使用 AutoMapper 将目标对象映射到源对象中的子对象?

标签 c# entity-framework automapper

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

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 的值映射到 dest,然后将 source.Categories 映射到 dest .类别。 AutoMapper 可以吗?

我已经试过了,当它失败时我并不感到惊讶:

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

这是我收到的异常:

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

最佳答案

在与 OP 讨论后,发现他的主要需求是快速将源对象内的子对象/嵌套对象映射到展平的目标对象。他不想为目的地的每个属性都编写一个映射。

这里有一个方法可以实现这一点:

  • 定义一个映射Product -> ProductViewModel用于展平 Product 的成员
  • 定义一个映射CategoryCategoryViewModel
  • 定义一个映射ProductWithCategories -> ProductViewModel映射类别,然后在后图中映射 Product :

    config.CreateMap<ProductWithCategories, ProductViewModel>() .ForMember(q => q.Id, option => option.Ignore()) // flattened in AfterMap .ForMember(q => q.Categories, option => option.MapFrom(q => q.Categories)) .AfterMap((src, dst) => Mapper.Map(src.Product, dst));

关于c# - 如何使用 AutoMapper 将目标对象映射到源对象中的子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35573006/

相关文章:

sql - 使用 Entity Framework 4.1 for Oracle 时,长列名会产生错误

c# - 这是 AutoMapper 2.0.0 和 2.2.0 之间的重大变化吗?

c# - 使用 AutoMapper 从 ICollection<EFEntity> 映射到 ICollection<ViewModel> 到 ICollection<Object>

c# - ASP.NET MVC - 使用 Automapper 进行映射

c# - 如何在 tableLayoutPanel 中设置 columnspan

c# - 空用户输入异常c#

c# - 用于打开文件的 WPF 命令行参数给出无限循环

c# - 适用于 Windows 7 64 位的 SQLite3.dll

sql - 在 Entity Framework 中创建关联?

c# - 将 ASP.NET 4 Web 应用程序部署到 IIS6 服务器后,工作进程回收导致其大部分时间停止工作