Search code examples
c#constructormappingmapperly

Using Mapperly Library for Custom Constructor Mapping C#


I am currently utilizing the Mapperly library and encountering an issue with generating a mapper. I am working with two classes, which are defined as follows:

class Class1
{
    public int Version { get; }
}

and

class Class2
{
    public Version Version { get; }
    
    Class2(Version version) {Version = version;}

}

The challenge arises with the Version class, which includes a constructor requiring two parameters:

public Version(int major, int minor)

With AutoMapeper I would go with

.ConstructUsing(x => new Version(x, 0))

However, it appears that Mapperly does not support this functionality, or I have yet to discover a solution. The documentation does not provide clarity for my specific situation. Could you please advise if it is possible to achieve the desired mapper generation with Mapperly, and if so, how I might go about it?

Thank you in advance.


Solution

  • You should be able to use a user-implemented mapping method which to map from an integer to a Version: docs. Just add a method like the following to your mapper definition:

    private Version MapMajorVersion(int majorVersion) => new Version(majorVersion, 0);