使用AutoMapper协助遍历对象

时间:2018-06-25 16:42:57

标签: c# automapper

我遇到了一些地图问题,希望社区能够提供帮助。我正在使用AutoMapper 6.0版来建立对象之间的连接。我有三个具有以下结构的对象(由于数据本身并不重要,所以使用通用名称):

public ObjectA {
    string field1 { get; set; }
    string field2 { get; set; }
    string field3 { get; set; }
    string field4 { get; set; }
}

public ObjectB {
    string field1 { get; set; }
    string field2 { get; set; }
    List<ObjectC> ObjectC { get; set; }
}

public ObjectC {
    string field3 { get; set; }
    string field4 { get; set; }
}

我有几个这样的地图设置:

Mapper.Initialize(cfg => {
    cfg.CreateMap<ObjectC, ObjectA>();
    cfg.CreateMap<ObjectB, ObjectA>();
});

这使我陷入困境。 ObjectA是数据库表及其字段的直接表示,我想使用ObjectB使用ObjectA对表中的条目进行检查,并添加所有尚未存在的表存在。我的问题是我似乎不了解如何通过ObjectBObjectAAutoMapper之间建立正确的连接,在其中我检查ObjectB可以创建的每个可能的变体ObjectA中的。

最终目标应为:

ObjectA objectA = // mapped data from ObjectB with the contents of List Item [0]
var objectAExists = _dataHandlers.GetObjectA;
if (objectAExists)
{
   // some code to return use to iterate back that this variant is in the DB already
   log.Info("ObjectA Already Exists");
}
else
{
    var results = storeContents(objectA);
    log.Info("New Contents Stored");
}
// return to top of iteration and this time process with contents using ObjectB.ObjectC[1] being used, and so on.

我尝试了一系列方法,例如:

// try to iterate through each List item...
for (int i = 0; i < ObjectB.ObjectC.Count; i++) {  
    //I wanted this to map the contents like so:
    ObjectA objectA = new ObjectA() {
        Field1 = ObjectB.Field1,
        Field2 = ObjectB.Field2,
        Field3 = ObjectB.ObjectC[i].Field3,
        Field4 = ObjectB.ObjectC[i].Field4
    }
    // but I couldn't figure out how to make a similar association using AutoMapper...
}

// tried to iterate through each with a foreach loop... but was in a similar situation as above... 
foreach (var objectC in ObjectB.ObjectC)  { // some code... }

// I tried double mapping...
    var objectA = Mapper.Map<ObjectA>(ObjectB);
    objectA = Mapper.Map<ObjectA>(objectC); // new problem hits here
// when I attempted to add the data from the new mapping, it overwrote the data populated by the first mapping...
// Change '=' to '+=' wasn't possible, so that didn't help...

// altering the mapper...
   cfg.CreateMap<ObjectB, ObjectA>()
       .Include<ObjectC, ObjectA>();

甚至尝试过使用类型转换器...但是遇到了另一堵墙。不用说,我的想法还不够,而且AutoMapper文档似乎没有提供足够的信息来解决此问题。任何可以向我指出解决方案的建议都将不胜感激...

谢谢大家。

1 个答案:

答案 0 :(得分:0)

也许您正在寻找的是一个映射表达式,该表达式指定仅应在目标属性尚未设置的情况下对其进行映射。这样,映射是有条件的。如果尚未设置destination属性,则将从源映射它。如果目标位置已被填充,则不会被覆盖。

Mapper.Initialize(
    cfg =>
    {
        cfg.CreateMap<ObjectB, ObjectA>()
            .ForMember(src => src.field2,
                opt => opt.ResolveUsing((src, dest) => 
                    dest.field2 = dest.field2 ?? src.field2
                ));
    });