WDu*_*ffy 2 c# asp.net-mvc automapper
我遇到了一个我似乎无法解决的自动配置问题.
我有一个类型联系的实体,我正在尝试将这些列表映射到字典.但是,映射只是没有做任何事情.源字典保持为空.有人可以提供任何建议吗?
以下是Contact类型的简化版本
public class Contact
{
public Guid Id { get; set ;}
public string FullName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的自动配置如下所示
Mapper.CreateMap<Contact, KeyValuePair<Guid, string>>()
.ConstructUsing(x => new KeyValuePair<Guid, string>(x.Id, x.FullName));
Run Code Online (Sandbox Code Playgroud)
我的调用代码如下所示
var contacts = ContactRepository.GetAll(); // Returns IList<Contact>
var options = new Dictionary<Guid, string>();
Mapper.Map(contacts, options);
Run Code Online (Sandbox Code Playgroud)
Gab*_*abe 10
这应该适用于以下,不需要Mapper ......
var dictionary = contacts.ToDictionary(k => k.Id, v => v.FullName);
Run Code Online (Sandbox Code Playgroud)
AutoMapper网站上的文档非常粗略.据我所知,第二个参数Mapper.Map仅用于确定返回值应该是什么类型,并且实际上没有被修改.这是因为它允许您基于现有对象执行动态映射,该对象的类型仅在运行时已知,而不是对泛型中的类型进行硬编码.
所以你的代码中的问题是你没有使用返回值Mapper.Map,它实际上包含最终转换的对象.这是我已经测试过的代码的修改版本,并按预期正确返回转换后的对象.
var contacts = ContactRepository.GetAll();
var options = Mapper.Map(contacts, new Dictionary<Guid, string>());
// options should now contain the mapped version of contacts
Run Code Online (Sandbox Code Playgroud)
虽然利用通用版本而不是仅仅为了指定类型而构造不必要的对象会更有效:
var options = Mapper.Map<List<Contact>, Dictionary<Guid, string>>(contacts);
Run Code Online (Sandbox Code Playgroud)
这是一个可以在LinqPad中运行的工作代码示例(运行示例需要AutoMapper.dll的程序集引用.)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
7218 次 |
| 最近记录: |