将内部映射器添加到AutoMapper映射配置文件

时间:2019-07-29 15:34:36

标签: c# asp.net-core automapper

我正在尝试将源类型的对象映射到目标,并且它需要一些内部映射。我已经创建了一个这样的自定义映射器。

public class CustomerMappingProfile : ITypeConverter<Customer, CustomerDTO>
    {
        public CustomerDTO Convert(Customer input, CustomerDTO destination, ResolutionContext context)
        {
            var CustomerDTO = new ObjectMapper<CustomerDTO, Customer>().Apply(input);
            CustomerDTO.NumbOfSeniorYears = input.YearsList != null ? input.YearsList.Count(p => p.Seniority == SeniorityEnum.Senior) : 0;
            CustomerDTO.NumOfYears = input.NumOfYears.Count();
            CustomerDTO.SearchTypeSelection = input.SearchTypeSelection;
            CustomerDTO.UpgradeTypes = input.UpgradeTypes;
            if (input.Rewards.Any())
            {
                foreach (var reward in input.Rewards)
                {
                    var result = Mapper.Map<Customer.Rewards, RewardsDTO>(reward);
                    CustomerDTO.Rewards.Add(result);
                }
            }
            if (input.EliteLevel == -1)
            {
                CustomerDTO.EliteLevel = null;
            }
            else
            {
                CustomerDTO.EliteLevel = input.EliteLevel;
            }
            var softLoggedIn = Helper.Util.PersServicesUtil.GetCharacteristic(input.Characteristics, "SOFT_LOGGED_IN");
            if (softLoggedIn != null)
            {
                if (softLoggedIn.Equals("true"))
                {
                    CustomerDTO.SoftLoginIndicator = true;
                }
                else
                {
                    CustomerDTO.SoftLoginIndicator = false;
                }
            }
            CustomerDTO.SessionId = Customer.SessionId.ToLower();
            return CustomerDTO;
        }


    }

我创建了映射配置文件

  public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Rewards, RewardsDTO>();
            CreateMap<Customer, CustomerDTO>().ConvertUsing(new CustomerMappingProfile());;
        }
    }

并将映射progile注入startup.cs

var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MappingProfile());
            });

            services.AddSingleton(sp => config.CreateMapper());

但是我在内部映射的InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.行的自定义映射器中遇到了异常Mapper.Map<Customer.Rewards, RewardsDTO>(reward);

关于如何添加内部映射的任何想法?

1 个答案:

答案 0 :(得分:2)

我相信您所有的问题都可以通过编写适当的AutoMapper配置来解决。

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Rewards, RewardsDTO>();
        CreateMap<Customer, CustomerDTO>()
            .ForMember(destination => destination.NumbOfSeniorYears, options =>
                options.MapFrom(source => source.YearsList.Count(p => p.Seniority == SeniorityEnum.Senior)))
            .ForMember(destination => destination.NumOfYears, options =>
                options.MapFrom(source => source.NumOfYears.Count()))
            .ForMember(destination => destination.EliteLevel, options =>
                options.Condition(source => source.EliteLevel != -1))
            .ForMember(destination => destination.SoftLoginIndicator, options =>
                options.MapFrom((source, dest, context) =>
                    Helper.Util.PersServicesUtil
                        .GetCharacteristic(source.Characteristics, "SOFT_LOGGED_IN")
                        ?.Equals("true") ?? false))
            .ForMember(destination => destination.SessionId, options =>
                options.MapFrom(source => source.SessionId.ToLower()));
    }
}

从您的代码来看,我认为您正在混淆一些东西,例如,映射配置文件的概念与类型转换器的概念。您也不必显式映射仍将被映射的成员(SearchTypeSelectionUpgradeTypes)。

我强烈建议您访问AutoMapper documentation site,以便您可以自己建立扎实的知识基础。有了您的映射代码,您将可以更高效,更短地编写代码。

还有一件事。恕我直言,您的注入逻辑看起来很奇怪。您是否问过自己,您真的需要AutoMapper的自定义单例吗?为什么不只打电话给AddAutoMapper()?请参阅documentation示例,了解如何在ASP.NET Core中使用AutoMapper。