Mapster,尝试使用许多没有默认的构造函数映射到 class 的字段并失败
Mapster, try map to field of class with many constructor without default and fail
我正在尝试学习 Mapster。我有 class 个这样的
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));
现在,如果我尝试映射对象 - 一切都很好,但如果我将第二个构造函数添加到 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 在运行时遇到异常:
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'
我尝试阅读有关 ConstructUsing
和 MapWith
的文档,这不是我需要的(或者我做错了什么)。我该怎么做?
我找到了。只需使用
config.ForType<Sub, Sub>().MapToConstructor(true);
我正在尝试学习 Mapster。我有 class 个这样的
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));
现在,如果我尝试映射对象 - 一切都很好,但如果我将第二个构造函数添加到 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 在运行时遇到异常:
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'
我尝试阅读有关 ConstructUsing
和 MapWith
的文档,这不是我需要的(或者我做错了什么)。我该怎么做?
我找到了。只需使用
config.ForType<Sub, Sub>().MapToConstructor(true);