我有以下情况:
源类:
public class Source
{
public int? A { get; set; }
public int? B { get; set; }
public int? C { get; set; }
}
目的地类别:
public class Destination
{
public int A { get; set; }
public bool AIsNull { get; set; }
public int B { get; set; }
public bool BIsNull { get; set; }
public int C { get; set; }
public bool CIsNull { get; set; }
}
我想通过以下方式从Source => Destion获取映射:
编辑,经过一些研究:
class Program
{
static void Main(string[] args)
{
var srcClass = new SourceClass { Value1 = 10, Value2 = null, Value3 = 20 };
Mapper.Initialize(cfg =>
{
cfg.ClearPrefixes();
cfg.RecognizePostfixes("IsNull");
cfg.CreateMap<SourceClass, TargetClass>();
});
var targetClass = Mapper.Map<SourceClass, TargetClass>(srcClass);
}
}
public class SourceClass
{
public int? Value1 { get; set; }
public int? Value2 { get; set; }
public int? Value3 { get; set; }
}
public class TargetClass
{
public bool Value1IsNull { get; set; }
public bool Value2IsNull { get; set; }
public bool Value3IsNull { get; set; }
}
在这种情况下,魔术仍然没有发生
答案 0 :(得分:0)
我认为类似这样的方法应该可行,我没有在VS中对此进行过测试,因此请与一粒盐一起使用。
var map = CreateMap<Source,Target>();
map.ForAllMembers(opt => opt.Ignore());
map.ForMember(dest => dest.A, opt => opt.MapFrom( src => src.A.HasValue ? src.A.Value : 0));
map.ForMember(dest => dest.AIsNull, opt => opt.MapFrom( src => src.A.HasValue ? true : false));