基于动态条件的自动映射器

Automapper based on dynamic condition

我有一个网站 API 可以阅读下面的数据

我正在使用 automapper 来映射 classes

这是我的实体class

class Country
{
  public int id {get;set}
  public string CountryEnglishName {get;set;}
  public string CountryArabicName {get;set;}

}

我的 DTO 如下所示

class CountryDTO
{
  public int id {get;set}
  public string Country {get;set;}

}

如果用户将 API 参数作为“English”传递,则 CountryDTO class 字段 Country 应包含 CountryEnglishName

如果用户将 API 参数作为“阿拉伯语”传递,则 Country 应包含 CountryArabicName

我们可以用 automapper 解决这个问题吗?

你可以做到

CreateMap<Country, CountryDTO>().ForMember(x => x.Country, opt => opt.MapFrom(src => string.IsNullOrEmpty(src.CountryEnglishName) ? src.CountryArabicName : src.CountryEnglishName));

这是一个示例,您可以在其中使用可以保存 api 参数的客户解析器

using System;
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp7
{
    class Country
    {
        public int id { get; set; }
        public string CountryEnglishName { get; set; }
        public string CountryArabicName { get; set; }

    }

    class CountryDTO
    {
        public int id { get; set; }
        public string Country { get; set; }

    }

    public interface IX
    {
        string ApiParameter { get; }
    }

    public class X : IX
    {
        // Here is where you get the parameter from the request if you need it from let's say the HttpContext, change this and you will see a differnt output
        public string ApiParameter => "English";
    }

    public class CustomResolver : IMemberValueResolver<object, object, string, string>
    {
        private readonly string _parameter;

        public CustomResolver(IX x)
        {
            _parameter = x.ApiParameter;
        }

        public string Resolve(object source, object destination, string sourceMember, string destinationMember, ResolutionContext context)
        {
            var c = (Country) source;
            return _parameter == "English" ? c.CountryEnglishName : c.CountryArabicName;
        }
    }

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Country, CountryDTO>()
                .ForMember(x => x.Country, opt => opt.MapFrom<CustomResolver,string>(src=>src.CountryEnglishName));

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            services.AddAutoMapper(typeof(MappingProfile));
            services.AddScoped<IX, X>();
            var mapper = services.BuildServiceProvider().GetRequiredService<IMapper>();
            var c = new Country()
            {
                CountryEnglishName = "A",
                CountryArabicName = "B"
            };
            var dto = mapper.Map<Country, CountryDTO>(c);
            Console.WriteLine(dto.Country);
        }
    }
}