有两个类:
public class Foo
{
public String Name { get; set; }
}
public class FooWrapper
{
public Foo Foo { get; set; }
}
目标是将FooWrapper映射到Foo。
[TestMethod]
public void FooWrapperDerived_CanBeAssignToFoo_WithoutAfterMap()
{
FooWrapper fw = new FooWrapper { Foo = new Foo { Name = "foo" } };
Foo foo = new Foo();
Mapper.CreateMap<Foo, Foo>();
Mapper.CreateMap<FooWrapper, Foo>();
//.ConstructUsing(w => w.Foo); //Actual:<(null)>
//.ConvertUsing(w => w.Foo); //Actual:<(null)>
//.ForAllMembers(c => c.MapFrom(w => w.Foo)); //Actual:<MvcArch.Tests.Common.Foo>
//.ForAllMembers(c => c.ResolveUsing(w => w.Foo)); //Actual:<MvcArch.Tests.Common.Foo>
//.ForAllMembers(c => c.UseValue(fw.Foo)); //Actual:<MvcArch.Tests.Common.Foo>
//.ForMember(f => f, c => c.MapFrom(w => w.Foo)); //AutoMapper configuration exception
//.ForMember(f => f.Name, c => c.ResolveUsing(w => w.Foo)); //Actual:<MvcArch.Tests.Common.Foo>
//.ForMember(f => f.Name, c => c.MapFrom(w => w.Foo.Name)); //works, but I don't want to repeat each property in the configuration
Mapper.Map<FooWrapper, Foo>(fw, foo); //uses the Map defined for the base type FooWrapper
Assert.AreNotSame(foo, fw.Foo);
Assert.AreEqual("foo", foo.Name);
}
它使用AfterMap作为: Mapper.CreateMap()。AfterMap((w,f)=&gt; Mapper.Map(w.Foo,f)); 但是可以在不访问全局Mapper对象的情况下定义地图吗?