c# - 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'
我尝试阅读文档,关于ConstructUsing
andMapWith
这不是我需要的(或者我做错了什么)。我怎么能做到这一点?
解决方案
我发现。只需使用
config.ForType<Sub, Sub>().MapToConstructor(true);
推荐阅读
- java - 找不到“org.hibernate.SessionFactory”类型的 bean
- c# - 如何使用 C# 获取基类型类的值
- python - 将字典与整数作为值和键进行比较
- python - Pandas:如何检测数据框中的峰值点(异常值)?
- ajax - Flask Jinja2 页面在一段时间后冻结
- twig - 使用带有 Timber/Twig 的 ACF 库
- vba - 检查多个条件并存储值
- vuejs2 - Nuxt - 定义一次 const 并且可以在所有页面中使用
- javascript - 以“URL/value”形式提交搜索表单,不带查询字符串“?q=value”
- dialogflow-es - Dialogflow - 如何让代理理解训练短语中的位置?