MapFrom并不总是正确映射

时间:2014-11-28 16:22:05

标签: c# .net automapper

这是一段简单的代码:

 var map = Mapper.CreateMap<Contact, ContactDtoGrid>().
                    ForMember("executive_account", x => x.MapFrom(y => y.executive_account.Id)).
                    ForMember("executive_account_Name", x => x.MapFrom(y => y.executive_account.Name));

foreach (Contact c in allContacts)
{
     string accountNumber = accounts.Where(x=>x.Key==c.executive_account.Id).SingleOrDefault().Value;

     string protocolDescription = (protocolDefinitions.Where(x => x.ProtocolOptionSetValue == c.executive_protocol).Any()) ? protocolDefinitions.Where(x => x.ProtocolOptionSetValue == c.executive_protocol).SingleOrDefault().PortalDescription : string.Empty;


    if (protocolDescription != string.Empty)
      Console.Write(protocolDescription); //I do get an output so it's not always empty

    map.ForMember("executive_account_Number", x => x.MapFrom(y => accountNumber));
    map.ForMember("executive_protocol_desc", x => x.MapFrom(y => protocolDescription));

    var contactDto = Mapper.Map<Contact, ContactDtoGrid>(c);

}

因此除了始终为空字符串的executive_protocol_desc外,所有属性都正确映射。就像我在上面的评论中提到的那样,无论protocolDescription是否为空字符串都是如此。

我做错了什么?

感谢。

2 个答案:

答案 0 :(得分:0)

在方法中,你并没有真正做MapFrom,而是设置了一个值。由于automapper使用嵌套闭包,因此使用直接赋值更容易:

...
var contactDto = Mapper.Map<Contact, ContactDtoGrid>(c);
contactDto.executive_protocol_desc = protocolDescription;

如果你需要将它保存在映射器中,你应该能够将协议魔法作为表达式。这将允许您从foreach循环中提取协议描述。注意:我还简化了linq表达式。

map.ForMember("executive_protocol_desc", opt => opt.MapFrom(src =>
    protocolDefinitions.Any(pdef => pdef.ProtocolOptionSetValue == src.executive_protocol)) 
    ? protocolDefinitions.SingleOrDefault(pdef => pdef.ProtocolOptionSetValue == src.executive_protocol).PortalDescription
    : string.Empty)

答案 1 :(得分:0)

我从循环中取出这些线:

map.ForMember("executive_account_Number", x => x.MapFrom(y => accountNumber));
map.ForMember("executive_protocol_desc", x => x.MapFrom(y => protocolDescription));

在循环开始之前,我将其更改为:

map.ForMember(dest => dest.executive_protocol_desc, opt => opt.MapFrom(x => protocolDefinitions.Where(y => y.ProtocolOptionSetValue == x.executive_protocol.Value).SingleOrDefault().PortalDescription));
map.ForMember(dest => dest.executive_account_Number, opt => opt.MapFrom(x => accounts.Where(y => y.Key == x.executive_account.Id).SingleOrDefault().Value));

现在这个地图正确映射。