我有两个对象,我想使用AutoMapper属性映射它们,这些是我的目标对象:
public class ClaseB
{
public string UBLVersionID_nuevo { get; set; }
public ClaseB_inside objetoB_inside { get; set; }
}
public class ClaseB_inside
{
public string texto_inside { get; set; }
}
这是我的源类:
[MapsTo(typeof(ClaseB))]
public class ClaseA
{
[MapsToProperty(typeof(ClaseB), "objetoB_inside.texto_inside")]
public string texto { get; set; } = "texto prueba";
[MapsToProperty(typeof(ClaseB), "UBLVersionID_nuevo")]
public string texto2 { get; set; } = "texto 2 de prueba";
}
当我尝试映射时,我收到以下错误:
错误映射类型
并且有了这个改变:
[MapsTo(typeof(ClaseB))]
public class ClaseA
{
[MapsToProperty(typeof(ClaseB_inside), "objetoB_inside.texto_inside")]
public string texto { get; set; } = "texto prueba";
[MapsToProperty(typeof(ClaseB), "UBLVersionID_nuevo")]
public string texto2 { get; set; } = "texto 2 de prueba";
}
我在null
中获得了ClaseB.objetoB_inside
但ClaseB.UBLVersionID_nuevo
却有效。
我做错了什么?
答案 0 :(得分:0)
我认为问题在于您定义映射的方式。如果您没有使用Automapper属性并且正在通过静态API进行初始化,请考虑以下事项:
Mapper.Initialize(expression =>
{
expression.CreateMap<ClaseA, ClaseB>()
.ForMember(
from => from.objetoB_inside.texto_inside,
to => to.MapFrom(a => a.texto2));
});
此映射会导致以下异常:
Expression 'from => from.objetoB_inside.texto_inside' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead.
我认为这与属性定义的问题相同。
所以我建议实施以下内容:
public class MapsToClaseB : MapsToAttribute
{
public MapsToClaseB() : base(typeof(ClaseB)) { }
public void ConfigureMapping(IMappingExpression<ClaseA, ClaseB> mappingExpression)
{
mappingExpression.AfterMap(
(a, b) => b.objetoB_inside = new ClaseB_inside{texto_inside = a.texto});
}
}
然后你需要用这个装饰你的课:
[MapsToClaseB]