使用automapper映射列表数组

时间:2017-08-26 11:20:29

标签: c# automapper

我试图映射包含源类的对象数组,这些对象必须映射目标类。

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;}
}

我需要使用自动映射器从B类列表映射到List类A. 请帮助

1 个答案:

答案 0 :(得分:2)

这很简单。您必须分两步映射信息。

首先让我们简化你的例子:

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;}
}

要从B和C创建A的一个对象,您必须创建两个地图并相互使用它们:

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

我觉得没什么新鲜事。但现在是棘手的部分。它的工作原理相同:

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;}
}

我们需要另一张地图和自定义转换器:

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;
        }
    }
}

现在你可以使用它了:

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