Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Empty Collection instead of null when mapping with Mapster

Tags:

c#

.net

mapster

We have an huge data driven application that involves multiple systems therefore a lot of mapping is needed. Due to performance issues we are gonna migrate from AutoMapper to Mapster.

Everything's good so far with Mapster but when mapping the Collections Mapster returns null value instead of empty Collection.

Automapper used to return Empty Collections by default but I am unable to figure out how to do that in Mapster.

I have tried doing the following but it does not work

TypeAdapterConfig.GlobalSettings.ForDestinationType<ICollection>().IgnoreNullValues(true);

TypeAdapterConfig.GlobalSettings.ForType(typeof(ICollection), typeof(ObservableCollection<>))
                        .IgnoreNullValues(true);

TypeAdapterConfig.GlobalSettings.ForType(typeof(ObservableCollection<>), typeof(ICollection))
                        .IgnoreNullValues(true);

Any help would be great

like image 299
Hannan Ayub Avatar asked Oct 13 '25 03:10

Hannan Ayub


1 Answers

I got it working thanks to Mapster team. Posting it here in case anyone else needs it

You can either configure it explicitly by:

TypeAdapterConfig.GlobalSettings.Default
    .AddDestinationTransform((IReadOnlyList<ChildDto> list) => list ?? new List<ChildDto>());

Mapster has also added generic support for AddDestinationTransform

config.Default.AddDestinationTransform(DestinationTransform.EmptyCollectionIfNull);

This worked for me.

like image 75
Hannan Ayub Avatar answered Oct 14 '25 16:10

Hannan Ayub