2

クラス(エンティティ)をマッピングしたいのですが、

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
   //...
   //..
   //.
}

次のクラス (ビュー モデル) に:

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 で可能ですか?

4

2 に答える 2

7

これをテストしたところ、単独で動作します...

        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);
于 2012-10-31T18:22:38.493 に答える
1

Automapper handles flattening automatically, which seems to be what you're asking for here. It's in the reverse direction from the way it's normally done, though, so it's possible it will choke. If it does, you can handle it using individual .ForMember() mappings.

In your case, it would look something like the following:

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

I don't have the ability to run this through an environment right this second so please point out any syntactical errors and I'll correct them.

于 2012-10-31T18:13:10.810 に答える