簡體   English   中英

自動映射器使用屬性C#

[英]automapper working with attributes c#

我有兩個對象,我想使用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";
}

我在ClaseB.objetoB_inside得到null ,但是ClaseB.UBLVersionID_nuevo有效。

我究竟做錯了什么?

我認為問題在於您定義映射的方式。 如果您不使用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. 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.

我認為Attributes定義也存在同樣的問題。

因此,我建議實施以下內容:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM