我有两个非常简单的对象:
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
属性的属性。在这种情况下,我需要读取属性值以找到目标属性。源属性的值用于查找要注入到目标属性中的值(借助于字典)。一个例子胜过千言万语...
例如:
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"
通过MapTo
属性,Key
属性映射到MyValueProperty
,并且分配的值为"MyValue",因为源属性值是"MyKey",它通过字典映射到"MyValue"。
使用AutoMapper是否可以实现这一点?当然,我需要一个适用于每个对象的解决方案,而不仅仅是Category/CategoryDto。