簡體   English   中英

如何使用Automapper完成以下映射?

[英]How can I accomplish the following mapping with Automapper?

我想映射類(實體),

public class Source {
   public int x;
   public string y;
   public bool z;

   public int a;
   public int b;
   public int c;

   //bunch of other fields
   //...
   //..
   //.
}

到以下類(View Model):

public class Destination {
   public MyClass1 A;
   public MyClass2 B;
}

其中MyClass1,MyClass2的定義如下:

public class MyClass1 {
   public int x;
   public string y;
   public bool z;
}

public class MyClass2 {
   public int a;
   public int b;
   public int c;
}

Automapper有可能嗎?

剛試過這個,它就是孤立地工作了......

        Mapper.CreateMap<Source, MyClass1>();
        Mapper.CreateMap<Source, MyClass2>();

        Mapper.CreateMap<Source, Destination>()
            .ForMember(x => x.A, m => m.MapFrom(p => p))
            .ForMember(x => x.B, m => m.MapFrom(p => p));


        var source = new Source() { a = 1, b = 2, c = 3, x = 4, y = "test", z = true };
        var destination = new Destination() { A = new MyClass1(), B = new MyClass2() };
        Mapper.Map<Source, Destination>(source, destination);

Automapper手柄壓扁自動 ,這似乎是你問這里。 然而,它與通常的方式相反,所以它可能會窒息。 如果是,您可以使用單獨的.ForMember()映射來處理它。

在您的情況下,它看起來像下面這樣:

Mapper.CreateMap<Source, Destination>()
    .ForMember(cv => cv.Destination, m => m.MapFrom(
    s => new Class1(s.x, s.y, s.z))

我沒有能力在這個環境中運行這個,所以請指出任何語法錯誤,我會糾正它們。

暫無
暫無

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

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