AutoMapper 3.0如何映射特定属性

时间:2013-11-24 22:55:48

标签: automapper

所以问题是如何发送值 source.SendSomeWhere =“它被发送了吗?”;从起源到ChildDestination

以下是我的尝试...除source.SendSomeWhere属性外,一切正常。

  using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using AutoMapper;
    namespace UnitTestProject2
    {
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void TestMethod1()
            {
                Mapper.CreateMap<Origin, Destination>();
                Mapper.CreateMap<OrginChild, ChildDestination>();
                Mapper.CreateMap<Deeper, DeeperDestination>();
                Mapper.CreateMap<Origin, ChildDestination>().ForMember(x=>x.sendSomeWhere,opt=>opt.MapFrom(src=>src.SendSomeWhere)).ForAllMembers(x=>x.Ignore());
                Origin source = new Origin();
                source.Name = "Test";
                source.SendSomeWhere = "was it sent?";
                source.originChild = new OrginChild { Code = "test", Deep = new Deeper { MyCode = "really cool" } };
                Destination dto = Mapper.Map<Destination>(source);
                var sentinel = true;

            }

            public class Origin
            {
                public string Name { get; set; }
                public string SendSomeWhere { get; set; }
                public OrginChild originChild { get; set; }
            }
            public class OrginChild
            {
                public string Code { get; set; }
                public Deeper Deep { get; set; }
            }
            public class Deeper
            {
                public string MyCode { get; set; }
            }


            public class Destination
            {
                public string Name { get; set; }
                public ChildDestination originChild { get; set; }
            }

            public class ChildDestination
            {
                public string Code { get; set; }
                public string sendSomeWhere { get; set; }
                public DeeperDestination Deep { get; set; }
            }
            public class DeeperDestination
            {
                public string MyCode { get; set; }
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

这应该这样做:

Mapper.CreateMap<Origin, Destination>()
    .AfterMap((src, dest) => dest.originChild.sendSomeWhere = src.SendSomeWhere);

Mapper.CreateMap<OrginChild, ChildDestination>();

Mapper.CreateMap<Deeper, DeeperDestination>();