Config for nested mapping (original) (raw)

For example if you have parent and child classes.

class ParentPoco { public string Id { get; set; } public List Children { get; set; } public string Name { get; set; } } class ChildPoco { public string Id { get; set; } public List GrandChildren { get; set; } } class GrandChildPoco { public string Id { get; set; } }

And if you have setting on parent type.

TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig() .PreserveReference(true);

By default, children types will not get effect from PreserveReference.

To do so, you must specify all type pairs inside ParentPoco.

TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig() .PreserveReference(true); TypeAdapterConfig<ChildPoco, ChildDto>.NewConfig() .PreserveReference(true); TypeAdapterConfig<GrandChildPoco, GrandChildDto>.NewConfig() .PreserveReference(true);

Or you can set PreserveReference in global setting.

TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true);

Fork

You can use Fork command to define config that applies only specified mapping down to nested mapping without polluting global setting.

TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig() .Fork(config => config.Default.PreserveReference(true));

Ignore if string is null or empty

Another example, Mapster only can ignore null value (IgnoreNullValues), however, you use Fork to ignore null or empty.

TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig() .Fork(config => config.ForType<string, string>() .MapToTargetWith((src, dest) => string.IsNullOrEmpty(src) ? dest : src) );

Add a custom footer