Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use object-to-object Mapping AutoMapper

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to use object-to-object mapping AutoMapper", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use object-to-object mapping AutoMapper.

Introduction

AutoMapper supports the ability to construct custom value parsers, custom type converters, and value converters using static service locations:

Var configuration = new MapperConfiguration (cfg = > {cfg.ConstructServicesUsing (ObjectFactory.GetInstance); cfg.CreateMap ();})

Or dynamic service location for instance-based containers (including sub-containers / nested containers):

Var mapper = new Mapper (configuration, childContainer.GetInstance); var dest = mapper.Map (new Source {Value = 15})

You can use a configuration file to define a configuration. Then, by calling the IServiceCollection extension method AddAutoMapper at startup, let AutoMapper know which assemblies these profiles are defined in:

Services.AddAutoMapper (profileAssembly1, profileAssembly2 / *,... * /)

Or tag type:

Services.AddAutoMapper (typeof (ProfileTypeFromAssembly1), typeof (ProfileTypeFromAssembly2) / *,... * /)

You can now inject AutoMapper into the service / controller at run time:

Public class EmployeesController {private readonly IMapper _ mapper; public EmployeesController (IMapper mapper) = > _ mapper = mapper; / / use _ mapper.Map or _ mapper.ProjectTo}

Of course, there is also a lot of scalability, such as:

Custom type converter

Sometimes you need complete control over the conversion from one type to another. Typically, this is when a conversion function already exists when one type looks different from another, and you want to change from a "loose" type to a stronger type, such as the source type of a string to the target type of Int32.

For example, suppose our source type is:

Public class Source {public string Value1 {get; set;} public string Value2 {get; set;} public string Value3 {get; set;}}

But you want to map it to:

Public class Destination {public int Value1 {get; set;} public DateTime Value2 {get; set;} public Type Value3 {get; set;}}

If we try to map the two types as is, AutoMapper throws an exception (during mapping and configuration checking) because AutoMapper does not know any mapping from strings to int,DateTime or Type. To create mappings for these types, we must provide a custom type converter, and we can do so in three ways:

Void ConvertUsing (Func mappingFunction); void ConvertUsing (ITypeConverter converter); void ConvertUsing () where TTypeConverter: ITypeConverter

The first option is any function that has the source and returns the destination (there are also multiple overloads). This applies to simple situations, but it is clumsy in larger cases. In more difficult cases, we can create a custom ITypeConverter

Public interface ITypeConverter {TDestination Convert (TSource source, TDestination destination, ResolutionContext context);}

And provide AutoMapper with an instance of a custom type converter, or provide a type for a type that AutoMapper will instantiate at run time. The mapping configuration for our source / target type above will be:

Public void Example () {var configuration = new MapperConfiguration (cfg = > {cfg.CreateMap () .ConvertUsing (s = > Convert.ToInt32 (s)); cfg.CreateMap () .ConvertUsing (new DateTimeTypeConverter ()); cfg.CreateMap () .ConvertUsing (); cfg.CreateMap ();}); configuration.AssertConfigurationIsValid () Var source = new Source {Value1 = "5", Value2 = "01result.Value3.ShouldEqual 01Destination 2000", Value3 = "AutoMapperSamples.GlobalTypeConverters.GlobalTypeConverters+Destination"}; Destination result = mapper.Map (source); result.Value3.ShouldEqual (typeof (Destination));} public class DateTimeTypeConverter: ITypeConverter {public DateTime Convert (string source, DateTime destination, ResolutionContext context) {return System.Convert.ToDateTime (source) } public class TypeTypeConverter: ITypeConverter {public TypeConvert (string source, Type destination, ResolutionContext context) {return Assembly.GetExecutingAssembly () .GetType (source);}}

In the first mapping, from string to Int32, we only use the built-in Convert.ToInt32 function (provided as a method group). The next two are implemented using custom ITypeConverter.

The real power of custom type converters is that as long as AutoMapper finds source / target pairs on any mapping type, they can be used. We can build a set of custom type converters and use other mapping configurations on them without any other configuration. In the above example, we do not have to specify the string / int transformation again. Because the custom value parser must be configured at the type member level, the scope of the custom type converter is global.

Of course, there are many functions that need to be implemented in the actual project.

At this point, I believe you have a deeper understanding of "how to use object-to-object mapping AutoMapper". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report