ASP. NET Core Extension Library Entity Mapping Explanation

  • 2021-11-29 23:28:11
  • OfStack

Directory 1. Enable 2. Configure custom transformation logic STEP 3 Use 4. Specify attribute mapping relationships through attributes Step 5 Copy 6. Examples

In the hierarchical design pattern, The data between layers is usually transferred through the data transmission object (DTO), In most cases, the definition structures of data in each layer are similar. How to convert each other in these definition structures, we used AutoMapper library before, but AutoMapper has huge functions and complex use. In many scenarios, we may only need 1 basic object mapping function, so you can choose the lightweight AutoMapper implementation in the extension library at this time.

Entity mapping includes the following core functions:

There is no need to manually define the mapping relationship between types before using it Adopt dynamic compilation, cache conversion delegate and improve performance. Support to define attribute mapping relationship through attributes Support inserting custom transformation processing methods Support list conversion Support nested type conversion Support circular reference and reference relationship maintenance Support conversion mode or copy mode Support for generating predefined copy delegates
In order to maintain its lightweight, the following transformations are currently supported

Value type conversion
Compatible conversion between numeric types (such as int-- > uint)
Supports compatible conversions between value types and their nullable types
Dictionary type conversion
List type conversion
Conversion between enumerated types and string types
Conversion between structures and between structures and classes is not supported

Step 1 Enable

There are two ways to enable lightweight entity mapping:

If you are using it with other functions of the extension library, you can use UseExtensions directly

  using IHost host = Host.CreateDefaultBuilder()
             // UseExtensions Will automatically inject Mapper
             .UseExtensions()
             .ConfigureServices(sc =>
             {
               //  Pass ConfigureLightweightMapper To configure the mapping 
               sc.ConfigureLightweightMapper(options =>
               {
                //
               });
             })
             .Build();
If you need to use it alone, it can be enabled by AddLightweightMapper method on IServiceCollection

  // Entity transformation 
  serviceDescriptors.AddLightweightMapper()
    .ConfigureLightweightMapper(options =>
               {
                //
               });

2. Configure custom transformation logic

You can configure the post-logic for setting entity transformations through AddConvert on the mapping settings, as shown below.


  // Entity transformation 
  serviceDescriptors.AddLightweightMapper()
    .ConfigureLightweightMapper(options =>
    {
      //  Pass AddConvert Customizable transformation logic 
      //  The following definitions are derived from SourceA Convert to TargetB Automatically set properties when C Value of 
      options.AddConvert<SourceA, TargetB>((mapper, a, b) =>
      {
        b.C = "C";
      });
    });

STEP 3 Use

You can use the GetMapper method of IMapperProvider or IMapper < , > Get the Mapper instance directly.

Through IMapperProvider

//  Pass IMapperProvider
var mapperProvider = host.Services.GetRequiredService<IMapperProvider>();
var mapper = mapperProvider.GetMapper<SourceA, TargetA>();
var targetA = mapper.Convert(sourceA);
Through IMapper < , >

var mapperB = host.Services.GetRequiredService<IMapper<SourceA, TargetB>>();
var targetB = mapperB.Convert(sourceA);

4. Specify attribute mapping relationships through attributes

The default mapping is based on the attribute name, and you can also specify it through the MapperPropertyNameAttribute feature.

MapperPropertyNameAttribute:

属性名 类型 说明
Name String 目标或源的名称
TargetType Type 映射到的目标类型
SourceType Type 映射到当前类型的来源类型

With SourceType or TargetType, you can flexibly set mapping relationships on source types or target types according to your needs.

Step 5 Copy

Entity mapping also provides a copy method by which source entity attributes can be copied to target entities.

Through IMapper < , > Make a default copy of the CopyTo method of:


var mapperB = host.Services.GetRequiredService<IMapper<SourceA, TargetB>>();
var targetB1 = new TargetB();
mapperB.CopyTo(sourceA, targetB1);
Defining Copy Delegates from Excluded Fields by DefineCopyTo Method

var mapperB = host.Services.GetRequiredService<IMapper<SourceA, TargetB>>();
 //  Copies only properties outside the specified field 
var copyProc = mapperB.DefineCopyTo(a =>
new
{
  a.A // Ignore attributes A
});
var targetB2 = new TargetB();
copyProc(sourceA, targetB2);

6. Examples

For the complete project of the above example, please refer to the GitHub example

The above is the ASP. NET Core Extension Library Entity Mapping Details. For more information about ASP. NET Core Extension Library Entity Mapping, please pay attention to other related articles on this site!


Related articles: