我发现AutoMapper的错误或者我需要覆盖的一些基于约定的行为。下面的代码重现了这个问题。如何让AutoMapper不要尝试在下面的场景中写入FooType
属性?
[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)
重载来执行实际的映射。