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

女生的网名这么多〃 提交于 2019-11-30 08:32:27

Previously

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

The problem here is mapping definitions are static, defined once and reused throughout the lifetime of the application. Before 3.3, you would need to re-define the mapping on every request, with the hard-coded value. And since the mapping configuration is created in a separate location than our mapping execution, we need some way to introduce a runtime parameter in our configuration, then supply it during execution.

This is accomplished in two parts: the mapping definition where we create a runtime parameter, then at execution time when we supply it. To create the mapping definition with a runtime parameter, we “fake” a closure that includes a named local variable:

Mapper.Initialize(cfg => {

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

For more information see this

For one or more 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>();
});

In mapping class

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

Finally I found the resolution. I was doing: Mapper.Initialize{ Mapping field from source to destination } in the App_start and adding this file to the global.asax--> Application_Start() --> GlobalConfiguration.

I need to add one more line inside my Mapper.Initialize which is cfg.CreateMissingTypeMaps = true;

Now this code will work for explicit mapping where two classes don't have the same structure and names of properties.

Apart from this, if we need to map properties of two class with the same structure the code Mapper.map(source, destination) will also work, which was not working earlier.

Let me know if someone is having difficulty with the solution. Thanks all for the above reply.

Another way that seems a bit cleaner is to make a MappingProfile class which inherits from the Profile class of AutoMapper

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

Then you initialize the mapping with Mapper.Initialize(c => c.AddProfile<MappingProfile>()); in your startup code

That will allow you to use the mapping anywhere by calling

destination1Collection = source1Collection.Select(Mapper.Map<Source1, Destination1>);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!