我发现什么是 AutoMapper 的错误或一些我需要覆盖的基于约定的行为。下面的代码重现了该问题。FooType
在下面的场景中,如何防止 AutoMapper 尝试写入属性?
[Test]
public void FooTypeShouldNotBeAltered()
{
AutoMapper.Mapper.CreateMap(typeof (TypeB), typeof (TypeA))
.ForMember("Foo", opt => opt.MapFrom("Foo"));
var typeA = new TypeA { FooType = "foo" };
var typeB = new TypeB { Foo = "bar" };
AutoMapper.Mapper.Map(typeB, typeA, typeof (TypeB), typeof (TypeA));
Assert.AreEqual("foo", typeA.FooType);
}
public class TypeA
{
public string Foo { get; set; }
public string FooType { get; set; }
}
public class TypeB
{
public string Foo { get; set; }
}
这是测试的输出:
Expected string length 3 but was 13. Strings differ at index 0.
Expected: "foo"
But was: "System.String"
-----------^
(对于它的价值,我很清楚(尽管这段代码不一定完全证明)AutoMapper 将属性的值设置为FooType
属性的类型名Foo
。)
现在我正在寻找一种方法来阻止这种情况的发生,而不使用基于泛型的重载或自定义解析器,并且我需要使用Map(source, dest, sourceType, destType)
重载来执行实际的映射。