[英]Map from one dictionary to another using automapper
在使用 automapper 時,我無法找到解決方案。 我的問題是我有一個源字典,我需要將源字典“映射”到一個新的字典,其中的鍵應該不同(基本上是“改變”源字典的鍵)我想我可能能夠為此使用 AutoMapper .. 所以我嘗試了以下操作:
private Source source = new Source
{
{ "Name", "Frodo" },
{ "LastName", "Bagginz" },
{ "Years", 32 }
};
[TestMethod]
public void CanMapDictionaryDictionaryUsingAutoMapper()
{
var configuration = new MapperConfiguration
(
cfg =>
cfg.CreateMap<Source, Destination>()
.ForMember(m => m["FirstName"], o => o.MapFrom(s => s["Name"]))
.ForMember(m => m["Surname"], o => o.MapFrom(s => s["LastName"]))
.ForMember(m => m["Age"], o => o.MapFrom(s => s["Years"]))
);
var mapper = configuration.CreateMapper();
var result = mapper.Map<Destination>(source);
Assert.IsTrue(result.ContainsKey("FirstName"));
Assert.IsTrue(result.ContainsValue("FirstName"));
Assert.IsTrue(result.ContainsKey("Surname"));
Assert.IsTrue(result.ContainsValue("Surname"));
Assert.IsTrue(result.ContainsKey("Age"));
Assert.IsTrue(result.ContainsValue("Age"));
}
}
public class Source : Dictionary<string, object>
{
}
public class Destination : Dictionary<string, object>
{
}
創建這兩個類只是為了確保一旦 MapperConfiguration 移動到 Profile 並且 Profile 被“全局”加載,我們不會只映射應用程序中的所有字典。
但是..以上結果出現以下錯誤:
消息:測試方法 DictionaryMapperTest.MapDictionary.CanMapDictionaryDictionaryUsingAutoMapper 拋出異常:AutoMapper.AutoMapperConfigurationException:成員的自定義配置僅支持類型上的頂級單個成員。 堆棧跟蹤:ReflectionHelper.FindProperty(LambdaExpression lambdaExpression) MappingExpression
2.ForMember[TMember](Expression
1 destinationMember, Action1 memberOptions) <>c.<CanMapDictionaryDictionaryUsingAutoMapper>b__1_0(IMapperConfigurationExpression cfg) line 23 MapperConfiguration.Build(Action
ctor(Action`1 configure) MapDictionary.CanMapDictionaryDictionaryDictionaryUsingAutoMapper() 第 20 行
我錯過了什么嗎? 有沒有人有更好的解決方案來做我試圖在上面實現的那種“映射”? 我有點卡住了……而且由於我在應用程序中的所有其他映射都使用 AutoMapper,因此能夠保持一致並將其全部保存在一個地方會很好。
免責聲明:我不建議使用字典來存儲這些值。 具有屬性( FirstName
、 LastName
、 Age
)的類比以屬性名稱作為鍵的字典更有意義。
話說回來:
你已經定義了你的Source
和Destination
,它們都是Dictionary<string, object>
。 如果你想要一個類將Source
映射到Destination
具有相同的值但不同的鍵,這個類會這樣做:
public class DictionaryMapper
{
private readonly static Dictionary<string, string> keyMap;
static DictionaryMapper()
{
keyMap = new Dictionary<string, string>
{
{ "Name", "FirstName" },
{ "LastName", "Surname" },
{ "Years", "Age" }
};
}
public Destination MapSourceToDestination(Source source)
{
var destination = new Destination();
foreach (string sourceKey in keyMap.Keys)
{
if (source.ContainsKey(sourceKey))
{
var destinationKey = keyMap[sourceKey];
var destinationValue = source[sourceKey];
destination.Add(destinationKey, destinationValue);
}
}
return destination;
}
}
我使用了一些額外的行和變量,以便更容易地看到發生了什么。
它將一個鍵到另一個鍵的映射存儲在字典中。 給定來源,它會查看字典中的所有鍵。 這些鍵是“源”鍵——即源字典中的鍵。
對於每個鍵,如果源字典具有該鍵,那么它將在keyMap
字典中查找目標鍵,並使用從keyMap
檢索到的鍵將源中的值添加到目標字典中。
輸出是一個Destination
字典,其值與源字典相同,但具有新鍵。
即使這可以通過 Automapper 完成,您可能會發現這更易於閱讀。
該類及其所有方法可以是static
。 不知道你是怎么用的,根據自己的需要調整吧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.