這裏是你可以怎麼做。
考慮以下方法:
public void CreateMapBasedOnDictionary<TSource, TDestination>(IDictionary<string, string> mapping_dictionary)
{
var mapping_expression = AutoMapper.Mapper.CreateMap<TSource, TDestination>();
foreach (var kvp in mapping_dictionary)
{
string source_property_name = kvp.Key;
string destination_property_name = kvp.Value;
Type member_type = typeof (TSource).GetProperty(source_property_name).PropertyType;
mapping_expression = mapping_expression.ForMember(destination_property_name, x =>
{
typeof (IMemberConfigurationExpression<TSource>)
.GetMethod("MapFrom", new []{typeof(string)})
.MakeGenericMethod(member_type)
.Invoke(x, new[] { source_property_name });
});
}
}
然後你就可以使用它像這樣:
var translations = new Dictionary<string, string>()
{
{"FirstName", "Imie"},
{"LastName", "Nazwisko"},
};
CreateMapBasedOnDictionary<Source, Destination>(translations);
Source src = new Source()
{
FirstName = "My first name",
LastName = "My last name"
};
var dst = AutoMapper.Mapper.Map<Destination>(src);
下面是CreateMapBasedOnDictionary
方法的解釋:
AutoMapper已經有過載ForMember
,允許您按名稱指定目的地屬性。我們在這裏很好。
它也有MapFrom
的重載,允許您按名稱指定源屬性。然而,這種超載的問題在於它需要一個通用參數(TMember
)作爲屬性類型。
我們可以通過使用反射來獲取屬性的類型,然後動態調用MapFrom
方法和適當的TMember
類型參數來解決此問題。
你必須指定explicilty因爲名字都在這兩種類型的 –
你可能想看看完全不同:[用法AutoMapper當屬性名稱不同](http://stackoverflow.com/questions/2186160/usage-of-automapper-when-property-names-are-different?rq=1)。具體來說,你應該創建自己的[INamingConvention](http://stackoverflow.com/questions/3866369/how-do-i-get-automapper-to-deal-with-a-custom-naming-convention) –