首页 > 解决方案 > Mapster,尝试映射到具有许多没有默认构造函数的类的字段并失败

问题描述

我正在尝试学习 Mapster。我有这样的课

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);
}

创建一个配置:

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));

现在,如果我尝试 map 对象-everythink 都可以,但是如果我将第二个构造函数添加到Sub

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 运行时异常:

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'

我尝试阅读文档,关于ConstructUsingandMapWith这不是我需要的(或者我做错了什么)。我怎么能做到这一点?

标签: c#.netmapster

解决方案


我发现。只需使用

config.ForType<Sub, Sub>().MapToConstructor(true);

推荐阅读