Automapper AddAfterMapAction不调用方法 [英] Automapper AddAfterMapAction not calling method
问题描述
我正在为Automapper配置文件映射使用全局配置.
I am using global configuration for Automapper profile mapping.
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 .
Now I am adding .AddAfterMapAction using Expression.
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());
It is not invoking the Test method when I am mapping using this line: var dest = mapper.Map<Student, StudentVM>(StudentService.GetStudent());
我在这里做错什么了吗?因为它应该在映射时调用Test方法.
Am I doing anything wrong here. As it should call the Test method while mapping.
推荐答案
实例化MappingConfiguration
后,您将无法修改地图.构建TypeMap
后,将创建执行计划,并且该执行计划不能更改.
You can't modify maps after MappingConfiguration
is instantiated. Once a TypeMap
is built, the execution plan is created and can't change.
您需要将该AfterMap
配置移动到您要配置的位置.
You need to move that AfterMap
configuration into where you're configuring.
这篇关于Automapper AddAfterMapAction不调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!