繁体   English   中英

AutoMapper 问题将实体映射到字典<guid, string></guid,>

[英]AutoMapper problem mapping Entity to Dictionary<Guid, string>

我的一个自动映射配置有问题,我似乎无法解决。

我有一个联系人类型的实体,我正在尝试将这些列表添加到字典中。 然而,映射只是没有做任何事情。 源字典保持为空。 任何人都可以提供任何建议吗?

下面是 Contact 类型的简化版本

public class Contact
{
    public Guid Id { get; set ;}
    public string FullName { get; set; }
}

我的自动映射配置如下

Mapper.CreateMap<Contact, KeyValuePair<Guid, string>>()
    .ConstructUsing(x => new KeyValuePair<Guid, string>(x.Id, x.FullName));

我的调用代码如下

var contacts = ContactRepository.GetAll(); // Returns IList<Contact>
var options = new Dictionary<Guid, string>();
Mapper.Map(contacts, options);

这应该适用于以下内容,不需要映射器......

var dictionary = contacts.ToDictionary(k => k.Id, v => v.FullName);

AutoMapper 网站上的文档非常粗略。 据我所知,Mapper.Map中的第二个参数仅用于确定返回值应该是什么类型,并没有实际修改。 这是因为它允许您基于现有的 object 执行动态映射,其类型仅在运行时已知,而不是在 generics 中硬编码类型。

所以你的代码中的问题是你没有使用Mapper.Map的返回值,它实际上包含最终转换的 object。 这是您的代码的修改版本,我已经测试并正确返回了您期望的转换后的对象。

var contacts = ContactRepository.GetAll();
var options = Mapper.Map(contacts, new Dictionary<Guid, string>());
// options should now contain the mapped version of contacts

尽管利用通用版本而不是仅仅为了指定类型而构造不必要的 object 会更有效:

var options = Mapper.Map<List<Contact>, Dictionary<Guid, string>>(contacts);

这是一个可以在 LinqPad 中运行的工作代码示例(运行该示例需要对AutoMapper.dll的程序集引用。)

希望这可以帮助!

GitHub AutoMapper 中的另一种解决方案:

https://github.com/AutoMapper/AutoMapper/issues/51

Oakinger[CodePlex] 刚刚写了一个小扩展方法来解决这个问题:

public static class IMappingExpressionExtensions 
{ 
public static IMappingExpression<IDictionary, TDestination> ConvertFromDictionary<TDestination>(this IMappingExpression<IDictionary, TDestination> exp, Func<string, string> propertyNameMapper) 
{ 
foreach (PropertyInfo pi in typeof(Invoice).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) 
{ 
if (!pi.CanWrite || 
pi.GetCustomAttributes(typeof(PersistentAttribute), false).Length == 0) 
{ 
continue; 
} 

string propertyName = pi.Name; 
propertyName = propertyNameMapper(propertyName); 
exp.ForMember(propertyName, cfg => cfg.MapFrom(r => r[propertyName])); 
} 
return exp; 
} 
} 

Usage: 

Mapper.CreateMap<IDictionary, MyType>() 
.ConvertFromDictionary(propName => propName) // map property names to dictionary keys 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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