【问题标题】:Automapper AddAfterMapAction not calling methodAutomapper AddAfterMapAction 不调用方法
【发布时间】:2020-02-24 10:32:57
【问题描述】:

我正在为 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();
    }
}

现在我正在使用 Expression 添加 .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);
    }

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

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

【问题讨论】:

  • @ZoltánTamási 感谢您的回复。它只允许 Expression in.AddAfterMapAction.

标签: asp.net-mvc automapper automapper-9


【解决方案1】:

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

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

【讨论】:

  • 你的意思是在 cfg.AddProfile() 之后但在 config.CreateMapper() 之前?
猜你喜欢
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
相关资源
最近更新 更多