[英]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.