AutoMapper.Mapper.CreateMap ()’已过时

我必须上课

class A { public int id {get; set;} } class B { public C c {get; set;} } class C { public int id {get; set;} public string Name {get; set;} } 

我的要求是将类A的id映射到类C的id。现在我所做的是:Mapper.CreateMap()。ForMember(des => des.C.Id,src => src.MapFrom(x = > x.id));

它工作正常。

现在看来,Auto mapper已经改变了它们的实现。 我收到的警告如下:

AutoMapper.Mapper.CreateMap()’已过时:’将在5.0版中删除动态创建地图。 使用MapperConfiguration实例并根据需要静态存储,或Mapper.Initialize。 使用CreateMapper创建映射器实例。

我需要映射具有不同名称和结构的类的一些属性。 对此有任何帮助。

先前

  Mapper.CreateMap() .ForMember(d => d.UserName, opt => opt.MapFrom(/* ????? */)); 

这里的问题是映射定义是静态的,定义一次并在应用程序的整个生命周期中重用。 在3.3之前,您需要使用硬编码值在每个请求上重新定义映射。 由于映射配置是在与映射执行不同的位置创建的,因此我们需要一些方法在配置中引入运行时参数,然后在执行期间提供它。

这由两部分完成:我们创建运行时参数的映射定义,然后是我们提供它时的执行时间。 要使用运行时参数创建映射定义,我们“伪造”包含命名局部变量的闭包:

 Mapper.Initialize(cfg => { string userName = null; cfg.CreateMap() .ForMember(d => d.UserName, opt => opt.MapFrom(src => userName) ); }); 

有关更多信息, 请参阅此

对于一个或多个class级

  cfg.CreateMissingTypeMaps = true; cfg.CreateMap() .ForMember(d => d.UserName, opt => opt.MapFrom(src => userName) ); cfg.CreateMap(); cfg.CreateMap(); }); 

在映射类中

  IMapper mapper = config.CreateMapper(); var source = new AbcEditViewModel(); var dest = mapper.Map(source); 

最后我找到了解决方案。 我正在做:在Mapper.Initialize{ Mapping field from source to destination }并将此文件添加到global.asax – > Application_Start() – > GlobalConfiguration。

我需要在Mapper.Initialize中添加一行,即cfg.CreateMissingTypeMaps = true;

现在,此代码将用于显式映射,其中两个类不具有相同的结构和属性名称。

除此之外,如果我们需要映射具有相同结构的两个类的属性,代码Mapper.map(source, destination)也将起作用,这在以前不起作用。

如果有人遇到解决方案有困难,请告诉我。 谢谢大家的上述回复。

另一种看起来更清晰的方法是创建一个inheritance自AutoMapper的Profile类的MappingProfile类

 public class MappingProfile:Profile { public MappingProfile() { CreateMap(); CreateMap(); ... } } 

然后使用Mapper.Initialize(c => c.AddProfile());初始化映射Mapper.Initialize(c => c.AddProfile()); 在你的启动代码中

这将允许您通过调用在任何地方使用映射

 destination1Collection = source1Collection.Select(Mapper.Map);