0

I'm try to learn Mapster. I have classes like this

class In
{
    public string A;
    public string B;
    public string C;
}

class Out
{
    public Sub Sub;
    public string C;
}

class Sub
{
    public string A; 
    public string B;
    
    public Sub(string a, string b)
        =>(A,B) = (a,b);
}

Create a config:

var mapper = new Mapper();

mapper.Config
    .ForType<In, Out>()
    .Map(@out => @out.C, @in=> @in.C)
    .Map(@out=> @out.Sub, @in => new Sub(@in.A, @in.B));

Now, if I try map object - everythink is ok, but if I add second costructor to Sub class

class Sub
{
    public string A; 
    public string B;
    
    public Sub(string a, string b)
        =>(A,B) = (a,b);

    public Sub(string a)=> A=a;
}

Mapster throe exception in runtime:

Error while compiling
source=UserQuery+In
destination=UserQuery+Out
type=Map

Error while compiling
source=UserQuery+Sub
destination=UserQuery+Sub
type=Map
No default constructor for type 'Sub', please use 'ConstructUsing' or 'MapWith'

I try read the docs, about ConstructUsing and MapWith and this is something not what I need (or am I doing something wrong). How I can do this?

srvr4vr
  • 173
  • 1
  • 9
  • If I add a default constructor, everything goes like clockwork. But in my real task - I can't do this. – srvr4vr Jan 18 '21 at 07:08
  • I have never used this library, but have you tried `.MapToConstructor(true)` see if this page helps https://github.com/MapsterMapper/Mapster/wiki/Constructor-mapping – TheGeneral Jan 18 '21 at 07:40
  • I understand this applies to the root object itself. And it doesn't fit my case. – srvr4vr Jan 18 '21 at 08:57

1 Answers1

6

I found. Just use

config.ForType<Sub, Sub>().MapToConstructor(true);
srvr4vr
  • 173
  • 1
  • 9