AutoMapper.Mapper.CreateMap <tsource,tdestination>()&#39;已过时

时间:2016-04-04 08:56:43

标签: c# asp.net asp.net-mvc-4 automapper automapper-3

我必须上课

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 =&gt; des.C.Id,src =&gt; src.MapFrom(x =&gt; x.id));

它工作正常。

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

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

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

3 个答案:

答案 0 :(得分:24)

以前

  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

对于一个或多个班级

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

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

在映射类

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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

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

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

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