[英]No mapping with AutoMapper with KeyValuePair<K, V>
I'm building a generic pretty-print method. 我正在构建一个通用的漂亮打印方法。 One of the special types that I want to handle separately is
KeyValuePair<TK,TV>
. 我想单独处理的一种特殊类型是
KeyValuePair<TK,TV>
。 In order to reduce the object to a known type, I thought I would map each KeyValuePair<TK,TV>
to a KeyValuePair<object, object>
. 为了将对象减少到已知类型,我想我会将每个
KeyValuePair<TK,TV>
映射到KeyValuePair<object, object>
。
The following code always produces 2 nulls in the Key
, Value
properties of proxy
. 以下代码始终在
proxy
的Key
, Value
属性中生成2个空Value
。
Mapper.CreateMap(o.GetType(), typeof(KeyValuePair<object, object>));
var proxy = Mapper.Map<KeyValuePair<object, object>>(o);
This non-generic version, on the other hand, works as expected: 另一方面,这个非通用版本按预期工作:
Mapper.CreateMap(o.GetType(), typeof(DictionaryEntry));
var proxy = Mapper.Map<DictionaryEntry>(o);
Why? 为什么?
o
at this stage has been tested to be a KeyValuePair<,>
. o
在这个阶段已被测试为KeyValuePair<,>
。
I'm using AutoMapper 3.2.1.0 on .NET 4.0. 我在.NET 4.0上使用AutoMapper 3.2.1.0。
DictionaryEntry
's Key
and Value
are both settable. DictionaryEntry
的Key
和Value
都是可设置的。 When you map to DictionaryEntry
, AutoMapper matches the Key
and Value
property and sets them. 映射到
DictionaryEntry
,AutoMapper会匹配Key
和Value
属性并设置它们。
It's unable to do this with KeyValuePair<TKey, TValue>
since it is immutable. KeyValuePair<TKey, TValue>
无法做到这一点,因为它是不可变的。 Therefore AutoMapper returns a new KeyValuePair<object, object>
with the Key
and Value
properties unset. 因此,AutoMapper返回一个新的
KeyValuePair<object, object>
,其中未设置Key
和Value
属性。
Normally, you could use ConstructUsing
to get around this: 通常,您可以使用
ConstructUsing
来解决这个问题:
Mapper.CreateMap<KeyValuePair<string, string>, KeyValuePair<object, object>>()
.ConstructUsing(kvp => new KeyValuePair<object, object>(kvp.Key, kvp.Value));
However, since you're not using this version of CreateMap
, this isn't possible. 但是,由于您没有使用此版本的
CreateMap
,因此无法实现。
You could create a simple extension method to do this instead though: 您可以创建一个简单的扩展方法来执行此操作:
public static class KeyValuePairExtensions
{
public static KeyValuePair<object, object> CastUp<TKey, TValue>(
this KeyValuePair<TKey, TValue> kvp)
{
return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
}
}
And then use it instead of AutoMapper: 然后使用它而不是AutoMapper:
var kvp = new KeyValuePair<string, string>("Hello", "World");
KeyValuePair<object, object> proxy = kvp.CastUp();
This would prevent you having to create a different mapping definition for every KeyValuePair
variation you use. 这将阻止您必须为您使用的每个
KeyValuePair
变体创建不同的映射定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.