Automapper 包含来自父 class 的所有属性

Automapper include all properties from parent class

我有以下代码:

using System;
using AutoMapper;

namespace AutoMapperPlayground
{
    public class Program
    {
        public static void Main()
        {
            var derived = new Derived {
                Title = "a",
                Base = new Base {
                    Id = 1,
                    Test = "b"
                }
            };


            Mapper.CreateMap<Derived, DerivedDTO>();
            

            var derivedDTO = Mapper.Map<DerivedDTO>(derived);
            Console.WriteLine("{0},{1},{2}", derivedDTO.Test, derivedDTO.Id, derivedDTO.Title);         
            
        }
    }

    public class Base
    {
        public int Id { get; set; }
        public string Test {get; set; }
    }

    public class Derived
    {
        
        public Base Base {get; set; }
        public string Title {get; set; }

    }

    public class BaseDTO
    {
        public int Id { get; set; }
        public string Test {get; set; }
    }

    public class DerivedDTO : BaseDTO
    {
        public string Title {get; set; } 
    }
}

输出是,0,a。 是否可以从 Base 填充 idtitle 属性?

Sample .net fiddle

谢谢

Flattening是AutoMapper的核心概念之一,约定俗成;您的 DTO 属性 名称需要以源类型中组合对象的 属性 名称为前缀:

public class DerivedDTO
{
    public int BaseId { get; set; }
    public string BaseTest { get; set; }
    public string Title { get; set; } 
}

但是,如果您想保留现有结构(DerivedDTO 继承自 BaseDTO),则需要手动定义这些映射:

Mapper.CreateMap<Derived, DerivedDTO>()
    .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Base.Id)),
    .ForMember(dest => dest.Test, opt => opt.MapFrom(src => src.Base.Test));

或者您可以创建从 BaseDerivedDTO 的映射,并将其包含在您的 Derived 映射中:

Mapper.CreateMap<Base, DerivedDTO>(); // Map Id and Test

Mapper.CreateMap<Derived, DerivedDTO>() // Map Title
    .IncludeMembers(src => src.Base); // Reuse above mapping to include Base Id and Test