1

我正在为 Automapper 配置文件映射使用全局配置。

public class StudentProfile : Profile
{
    public StudentProfile()
    {
        CreateMap<Student, StudentVM>()
            .ForMember(dest => dest.school, src => src.Ignore());
    }
}

映射器配置

public static class Configuration
{
    public static IMapper InitializeAutoMapper()
    {
        MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new StudentProfile());
        });

        config.AssertConfigurationIsValid();
        return config.CreateMapper();
    }
}

现在我正在使用表达式添加.AddAfterMapAction 。

static void Main(string[] args)
    {
        try
        {
            var mapper = Configuration.InitializeAutoMapper();

            foreach (var item in mapper.ConfigurationProvider.GetAllTypeMaps())
            {
                Expression<Action<int>> beforeMapAction = (x) => Test(x);
                item.AddAfterMapAction(beforeMapAction);
            }

            var dest = mapper.Map<Student, StudentVM>(StudentService.GetStudent());

            Console.ReadLine();
        }
        catch (Exception ex)
        {
        }
    }
    public static void Test(int x)
    {
        Console.WriteLine("X = {0}", x);
    }

当我使用这一行进行映射时,它没有调用 Test 方法:var dest = mapper.Map<Student, StudentVM>(StudentService.GetStudent());

我在这里做错什么了吗。因为它应该在映射时调用 Test 方法。

4

1 回答 1

2

MappingConfiguration实例化后无法修改地图。一旦TypeMap构建了 a ,执行计划就会创建并且不能更改。

您需要将该AfterMap配置移动到您正在配置的位置。

于 2020-02-25T13:55:42.607 回答