AutoMapper.Mapper.CreateMap<TSource,TDestination>()' 已过时

AutoMapper.Mapper.CreateMap<TSource,TDestination>()' is obsolete

我必须class喜欢

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;}
}

我的要求是将 class A 的 id 映射到 class 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 创建映射器实例。

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

以前

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

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

这分两部分完成:映射定义,我们在其中创建运行时参数,然后在执行时提供它。为了创建带有运行时参数的映射定义,我们“伪造”了一个包含命名局部变量的闭包:

Mapper.Initialize(cfg => {

string userName = null;
cfg.CreateMap<Source, Dest>()
    .ForMember(d => d.UserName, 
        opt => opt.MapFrom(src => userName)
    );
});

更多信息see this

一个或多个 classes

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

 cfg.CreateMap<AbcEditViewModel, Abc>();
 cfg.CreateMap<Abc, AbcEditViewModel>();
});

映射中class

  IMapper mapper = config.CreateMapper();
  var source = new AbcEditViewModel();
  var dest = mapper.Map<AbcEditViewModel, Abct>(source);

我终于找到了解决办法。我在做:Mapper.Initialize{ Mapping field from source to destination } 在 App_start 中并将此文件添加到 global.asax--> Application_Start() --> GlobalConfiguration.

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

现在这段代码将适用于两个 class 不具有相同结构和属性名称的显式映射。

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

如果有人对解决方案有困难,请告诉我。感谢以上大家的回复。

另一种看起来更简洁的方法是制作一个 MappingProfile class,它继承自 AutoMapper

的 Profile class
public class MappingProfile:Profile
{
    public MappingProfile()
    {
        CreateMap<Source1, Destination1>();
        CreateMap<Source2, Destination2>();
        ...
    }
}

然后在启动代码

中用Mapper.Initialize(c => c.AddProfile<MappingProfile>());初始化映射

这将允许您通过调用

在任何地方使用映射
destination1Collection = source1Collection.Select(Mapper.Map<Source1, Destination1>);