Entity mapping of asp.net core extension library

Time:2021-5-11

In the layered design pattern, the data between each layer is usually transferred through the data transfer object (dto). In most cases, the definition structures of the data of each layer are similar. How to transform each other in these definition structures? Before, we used the automapper library, but the function of automapper is huge and the use of it is more complex. In many scenarios, the function of automapper is complex, Maybe we only need some basic object mapping functions, then you can choose the lightweight automapper implementation in the extension library.

Entity mapping includes the following core functions:

  • There is no need to manually define the mapping relationship between types before use
  • Dynamic compilation and cache conversion are used to improve the performance.
  • Support to define attribute mapping relationship by attributes
  • Support insert custom conversion processing method
  • Support list conversion
  • Support nested type conversion
  • Support circular reference and reference relationship maintenance
  • Support conversion mode or copy mode
  • Support the generation of predefined copy delegation
  • To keep it lightweight, the following conversions are currently supported
    • Value type conversion
    • Compatible conversion between numeric types (such as int — > uint)
    • Compatible conversion between value type and its nullable type is supported
    • Dictionary type conversion
    • List type conversion
    • Conversion between enumeration type and string type
    • I won’t support itThe transformation between structs and between structs and classes

1、 Enable

There are two ways to enable lightweight entity mapping:

  • If you use it with other functions of the extension library, you can directly use useextensions
using IHost host = Host.CreateDefaultBuilder()
                         //Useextensions automatically injects mapper
                         .UseExtensions()
                         .ConfigureServices(sc =>
                         {
                             //Configure the mapping by configuring lightweight mapper
                             sc.ConfigureLightweightMapper(options =>
                             {
                                //
                             });
                         })
                         .Build();
  • If you need to use it alone, you can use the addlightweightmapper method on iservicecollection to enable it
//Entity transformation
    serviceDescriptors.AddLightweightMapper()
        .ConfigureLightweightMapper(options =>
                             {
                                //
                             });

2、 Configure custom conversion logic

You can configure the entity conversion of the corresponding settings by using addconvert on the mapping settingsPostpositionThe logic is as follows.

//Entity transformation
    serviceDescriptors.AddLightweightMapper()
        .ConfigureLightweightMapper(options =>
        {
            //The conversion logic can be customized by addconvert
            //The following definition automatically sets the value of property C when converting from sourcea to targetb
            options.AddConvert((mapper, a, b) =>
            {
                b.C = "C";
            });
        });

3、 Use

You can get mapper instances directly through the getmapper method of impapperprovider or impapper.

  • Through impapperprovider
//Through impapperprovider
var mapperProvider = host.Services.GetRequiredService();
var mapper = mapperProvider.GetMapper();
var targetA = mapper.Convert(sourceA);
  • Through impaper
var mapperB = host.Services.GetRequiredService>();
var targetB = mapperB.Convert(sourceA);

4、 Specifying attribute mapping relationships through attributes

The default mapping is based on the property name. You can also specify it through the mapperpropertynameattribute attribute attribute.

MapperPropertyNameAttribute:

Property name type explain
Name String The name of the target or source
TargetType Type Target type mapped to
SourceType Type The source type mapped to the current type

Through sourcetype or TargetType, you can flexibly set mapping relationship on source type or target type according to requirements.

5、 Copy

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

  • Copy by default through the copyto method of impapper:
var mapperB = host.Services.GetRequiredService>();
var targetB1 = new TargetB();
mapperB.CopyTo(sourceA, targetB1);
  • Define a copy delegate that excludes fields through the definecopyto method
var mapperB = host.Services.GetRequiredService>();
 //Copy only properties other than the specified field
var copyProc = mapperB.DefineCopyTo(a =>
new
{
    a. A // ignore attribute a
});
var targetB2 = new TargetB();
copyProc(sourceA, targetB2);

6、 Examples

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