我正在尝试使用带有自定义值转换器的 AutoMapper 在两个类 ParentA 和 ParentB 之间进行映射。但是,从 ParentB 映射回 ParentA 时我遇到了问题。
我们使用 Automapper 属性来进行映射
这是我的代码:
ParentA ssssssss = new ParentA { Id = 1, isActive = "Y", Name = "test" };
var response = automapper.Map<ParentB>(ssssssss);
response.Value = 500;
var yyyy = automapper.Map<ParentA>(response);
类定义:
public class ParentA
{
public int Id { get; set; }
public string Name { get; set; }
public string isActive { get; set; }
}
[AutoMap(typeof(ParentA), ReverseMap = true)]
public class ParentB
{
public int Id { get; set; }
public string Name { get; set; }
[ValueConverter(typeof(IntConverter))]
[SourceMember("isActive")]
public int Value { get; set; }
}
转换器是
public class IntConverter : IValueConverter<string, int>
{
public int Convert(string sourceMember, ResolutionContext context)
{
if (sourceMember == "Y") return 100;
if (sourceMember == "N") return 200;
if (sourceMember == "P") return 500;
return 1000;
}
public string Convert(int sourceMember, ResolutionContext context)
{
throw new NotImplementedException();
}
}
从 ParentA 到 ParentB 的映射工作正常。
从ParentB映射回ParentA时,失败,因为IntConverter中没有实现反向映射的Convert方法。
你能帮我在 IValueConverter 中实现反向映射吗?
这个怎么样:
public class IntConverter : IValueConverter<string, int>
{
public int Convert(string sourceMember, ResolutionContext context)
{
if (sourceMember == "Y") return 100;
if (sourceMember == "N") return 200;
if (sourceMember == "P") return 500;
return 1000;
}
public string Convert(int sourceMember, ResolutionContext context)
{
if (sourceMember == 100) return "Y";
if (sourceMember == 200) return "N";
if (sourceMember == 500) return "P";
return "your default";
}
}
但这似乎是显而易见的。您一定还有其他问题吗?