我有两个非常简单的对象:
public class CategoryDto
{
public string Id { get; set; }
public string MyValueProperty { get; set; }
}
public class Category
{
public string Id { get; set; }
[MapTo("MyValueProperty")]
public string Key { get; set; }
}
当使用 AutoMapper 将 Category
映射到 CategoryDto
时,我想要以下行为:
除了具有 MapTo
属性的属性外,属性应该照常映射。在这种情况下,我必须读取 Attribute 的值才能找到目标属性。源属性的值用于查找要注入(inject)目标属性的值(借助字典)。一个例子总比 1000 个单词好...
例子:
Dictionary<string, string> keys =
new Dictionary<string, string> { { "MyKey", "MyValue" } };
Category category = new Category();
category.Id = "3";
category.Key = "MyKey";
CategoryDto result = Map<Category, CategoryDto>(category);
result.Id // Expected : "3"
result.MyValueProperty // Expected : "MyValue"
Key
属性映射到 MyValueProperty
(通过 MapTo
属性),分配的值为“MyValue”,因为源属性值是映射(通过字典)到“MyValue”的“MyKey”。
这可以使用 AutoMapper 吗?我当然需要一个适用于每个对象的解决方案,而不仅仅是适用于 Category/CategoryDto。
最佳答案
我终于(经过这么多小时!!!!)找到了解决方案。 我与社区分享这个;希望它能帮助别人......
编辑:请注意,它现在更简单了(AutoMapper 5.0+),您可以按照我在这篇文章中的回答进行操作:How to make AutoMapper truncate strings according to MaxLength attribute?
public static class Extensions
{
public static IMappingExpression<TSource, TDestination> MapTo<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
Type sourceType = typeof(TSource);
Type destinationType = typeof(TDestination);
TypeMap existingMaps = Mapper.GetAllTypeMaps().First(b => b.SourceType == sourceType && b.DestinationType == destinationType);
string[] missingMappings = existingMaps.GetUnmappedPropertyNames();
if (missingMappings.Any())
{
PropertyInfo[] sourceProperties = sourceType.GetProperties();
foreach (string property in missingMappings)
{
foreach (PropertyInfo propertyInfo in sourceProperties)
{
MapToAttribute attr = propertyInfo.GetCustomAttribute<MapToAttribute>();
if (attr != null && attr.Name == property)
{
expression.ForMember(property, opt => opt.ResolveUsing(new MyValueResolve(propertyInfo)));
}
}
}
}
return expression;
}
}
public class MyValueResolve : IValueResolver
{
private readonly PropertyInfo pInfo = null;
public MyValueResolve(PropertyInfo pInfo)
{
this.pInfo = pInfo;
}
public ResolutionResult Resolve(ResolutionResult source)
{
string key = pInfo.GetValue(source.Value) as string;
string value = dictonary[key];
return source.New(value);
}
}
关于c# - 使用 AutoMapper 自定义映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706697/