AutoMapper

Source

ClassA A = new ClassA();

var config = new MapperConfiguration(cfg => cfg.CreateMap<ClassA, ClassB>());
var mapper = config.CreateMapper();
ClassB B = mapper.Map<ClassB>(A);

Ignore the specific properties

ClassA A = new ClassA();

var config = new MapperConfiguration(cfg => cfg.CreateMap<ClassA, ClassB>()
                                               .ForMember(x => x.PropertyA, y => y.Ignore())
                                               .ForMember(x => x.PropertyB, y => y.Ignore()));
var mapper = config.CreateMapper();
ClassB B = mapper.Map<ClassB>(A);

Custom condition for transforming specific property

using AutoMapper;

namespace CUB.KHBANK.BFF.Web.Infrastructure.AutoMapping
{
    public class CardsProfile : Profile
    {
        public CardsProfile()
        {
            Mapper.Initialize(cfg => 
            {
                // <TSource, TDestination>
                // Formember : Set src to dest, in this case src.Type is an enum, dest.Status is string
                CreateMap<DebitCardAccountSummary, DebitCardSummary>().ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Type.ToString()));
                // Transforming the List<DateTime> to List<string>, , these two lists are property in DebitCardAccountSummary and DebitCardSummary
                CreateMap<DateTime, string>().ConvertUsing(dt => dt.ToString("MMM yyyy", new CultureInfo("en-US")));
            });
        }
    }
}

in .NET Core 在Startup.cs注入

// Startup.cs
using AutoMapper;

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(x => x.AddProfile(new CardsProfile()));
}

// ========================================================================

// Controller
using AutoMapper;

namespace CUB.KHBANK.BFF.Web.Controllers.Card
{
    public class CardController : BaseController<CardController>
    {
        private readonly IMapper _mapper;

        public CardController(IMapper mapper)
        {
            this._mapper = mapper;
        }

        /// <summary>
        /// GetDebitCardAccountSummary
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("ActionName")]
        public async Task<ActionResult<Result<DebitCardAccountSummaryRes>>> ActionName()
        {
            var basicData = GetBasicData();

            var result = await _cardService.GetDebitCardAccountSummary(basicData);

            if (!result.IsSuccess)
            {
                return Ok(Fail(result.ReturnCode, result.ReturnMessage));
            }

            return Success(new DebitCardAccountSummaryRes
            {
                DebitCardAccountSummaryList = _mapper.Map<List<DebitCardSummary>>(result.Data.DebitCardAccountSummaryList)
            });
        }
    }
}