mapperly icon indicating copy to clipboard operation
mapperly copied to clipboard

Make it possible to choose between "replace" und "add" for collections

Open cremor opened this issue 1 year ago • 3 comments

Is your feature request related to a problem? Please describe. It seems like Mapperly currently uses the target property setter visibility in an "existing target object" mapper (void method) to decide if a collection (ICollection<T>) is completely replaced or if the items in the collection are just added. This is confusing/dangerous because a simple visiblity change on the setter can lead to different behavior of the mapper.

Describe the solution you'd like I'd like to configure if items are added to an existing collection or if a collection is replaced. One of the two possibilities should be the default for all collection properties, regardless of their setter visibility. If the currently active setting is to replace the collection, but the target property has no visible setter, then the generated code should call Clear() on the collection before adding the items.

Describe alternatives you've considered I know that I can call Clear() in a "before map" method. But the main problem here is that I might not even notice that I have to do this until I get a runtime bug.

Additional context In theory this also affects mappers that return the mapped object, but that would only show a difference if the constructor/object factory already adds items to the collection.

cremor avatar Aug 21 '23 06:08 cremor

Thanks for your feature request. I agree that this can be confusing and we'll think about the possible solutions to this problem

CommonGuy avatar Aug 21 '23 12:08 CommonGuy

Maybe it would even be possible to create a "merge" option? That might have a higher complexity to implement, but could also be useful. I assume that would require either a way to specify which property is compared for the equals check, or user provided method or IEqualityComparer for the equals check.

cremor avatar Aug 24 '23 09:08 cremor

Need this too - have a Tags property of List need to only add to this instead of replacing the List.

moxplod avatar Jun 15 '24 18:06 moxplod