[非专业翻译] 是对没有中文文档进行翻译的系列博客,文章由机翻和译者自己理解构成,和原文相比有所有不同,但意思基本一致。
因个人能力有限,如有谬误之处还请指正,多多包涵。
本文将说明 Mapster 如何映射只读属性
set
的属性Mapster 默认会自动映射非公开 set
的属性:
public class Order {
public string Id { get; set; }
public ICollection<OrderItem> Items { get; private set; }
}
给属性添加特性标签 [UseDestinationValue]
,未指定 set
的属性也能进行映射:
public class Order {
public string Id { get; set; }
[UseDestinationValue]
public ICollection<OrderItem> Items { get; } = new List<OrderItem>();
}
如果希望所有未指定 set
的 ICollection<>
都参与映射,那么可以使用 UseDestinationValue
方法进行配置:
TypeAdapterConfig.GlobalSettings.Default
.UseDestinationValue(member => member.SetterModifier == AccessModifier.None &&
member.Type.IsGenericType &&
member.Type.GetGenericTypeDefinition() == typeof(ICollection<>));
原文:https://www.cnblogs.com/staneee/p/14913664.html