我有以下型号:
public class A
{
public int a1;
public int a2;
public int a3;
public int a4;
public B b;
}
public class B
{
public int b1;
public int b2;
public C c;
}
public class C
{
public int c1;
public int c2;
}
public class A_DTO
{
public int a1;
public int a2;
public int a3;
public B_DTO b;
}
public class B_DTO
{
public int b1x;
public int b2;
public C_DTO c;
}
public class C_DTO
{
public int c1;
}
这是我的目标:
这是我正在使用的配置:
var config = new MapperConfiguration(
cfg => {
cfg.CreateMap<A, A_DTO>(MemberList.Source);
cfg.CreateMap<B, B_DTO>(MemberList.Source)
.ForMember(dest => dest.b1x, opt => opt.MapFrom(src => src.b1));
cfg.CreateMap<C, C_DTO>(MemberList.Source)
.ForSourceMember(src => src.c2, opt => opt.DoNotValidate());
}
);
这是我使用的测试数据:
var mapper = config.CreateMapper();
A a = new A()
{
a1 = 1,
a2 = 2,
a3 = 3,
a4 = 10,
b = new B
{
b1 = 4,
b2 = 5,
c = new C
{
c1 = 6,
c2 = 7
}
}
};
A_DTO aDto = new A_DTO();
mapper.Map(a, aDto);
这满足了我上面列出的所有条件,但最后一个条件除外,因为a4
上不存在A_DTO
,而且我仍然没有例外。 (如果我删除了.ForSourceMember(src => src.c2, opt => opt.DoNotValidate())
,它的确会抛出c2
的异常。)