1

有两个类:

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) => Mapper.Map(w.Foo, f)); 但是是否可以在不访问全局 Mapper 对象的情况下定义地图?

4

0 回答 0