简体   繁体   中英

map array of list using automapper

I'm trying to map an array of objects containing source classes, which has to be mapped destination classes.

class A
{
        public string Id { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public string Details { get; set; }
        public string Image { get; set; }
        public string Decription{ get; set;}
 }

class B
{
 public string Id { get; set; }
 public string Name { get; set; }
 public List<C> { get; set; }
}

class C{
  public string Url { get; set; }
  public string Details { get; set; }
  public string Image { get; set; }
  public string Decription{ get; set;}
}

I need to map from List of class B to List class A using auto mapper Kindly help

It's simple. You have to map the information in two steps.

First let's simplify your example:

class A {
    public string AttrB { get; set; }
    public string AttrC { get; set; }
}
class B {
    public string AttrB { get; set; }
}

class C {
    public string AttrC { get; set;}
}

To create one object of A from B and C you have to create two maps and use them after each other:

Mapper.CreateMap<B, A>();
Mapper.CreateMap<C, A>();

var c = new C { AttrC = "AttrCValue" };
var b = new B { AttrB = "AttrBValue" };
var a = Mapper.Map<A>(b); // a with the attribute values of b
Mapper.Map(c, a); // map the attribute values of c also into a

I think nothing new for you. But now comes the tricky part. It works with the same principle:

class A {
    public string AttrB { get; set; }
    public string AttrC { get; set; }
}
class B {
    public string AttrB { get; set; }
    public List<C> AttrBList { get; set; }
}

class C {
    public string AttrC { get; set;}
}

We need another map and a custom converter:

Mapper.CreateMap<B, A>();
Mapper.CreateMap<C, A>();
Mapper.CreateMap<B, IEnumerable<A>>().ConvertUsing<BConverter>();

class BConverter : ITypeConverter<B, IEnumerable<A>> {
    public IEnumerable<A> Convert(ResulutionContext ctx) {
        B b = (B)ctx.SourceValue;
        foreach(var aFromC in b.AttrBList.Select(c => Mapper.Map<A>(c))) { // map c attributes into an a object and return it (through Select it's a mapping for all items of the list AttrBList)
            Mapper.Map(b, aFromC); // push the attribute values from b to the aFromC object. Because this is inside the loop, it happens for every Item in the AttrBList array
            yield return aFromC;
        }
    }
}

Now you can use it:

var allAObjects = Mapper.Map<IEnumerable<A>>(listOfBObjects);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM