映射此属性需要什么表达式?

时间:2013-05-15 14:57:16

标签: automapper

我正在尝试使用AutoMapper映射两个 类似的对象,但是一个成员(AudioSummary)引发了以下异常:

无法映射EchoNestModel.AudioSummary上的以下属性:AudioSummary

添加自定义映射表达式,忽略,添加自定义解析程序或修改目标类型EchoNestModel.AudioSummary。

上下文:

- 从EchoNest.Api.AudioSummary映射到属性AudioSummary到EchoNestModel.AudioSummary

- 从EchoNest.Api.TrackProfile类型映射到EchoNestModel.Profile

抛出了“AutoMapper.AutoMapperConfigurationException”类型的异常。

映射定义

var map = Mapper.CreateMap<TrackProfile, Profile>();
map.ForMember(dest => dest.ForeignIds, opt => opt.ResolveUsing<ForeignIdResolver>());
map.ForMember(dest => dest.ForeignReleaseIds, opt => opt.ResolveUsing<ForeignReleaseIdResolver>());
map.ForMember(s => s.Media, t => t.Ignore());
map.ForMember(s => s.ProfileId, t => t.Ignore());
map.ForMember(s => s.AudioSummary, t => t.MapFrom(s => s.AudioSummary));

我添加了以下两行,但发生了完全不同的错误:

map.ForMember(s => s.AudioSummary.Profile, t => t.Ignore());
map.ForMember(s => s.AudioSummary.AudioSummaryId, t => t.Ignore());

Expression's =&gt; s.AudioSummary.Profile'必须解析为顶级成员而不是任何子对象的属性。

在子类型或AfterMap选项中使用自定义解析器。

参数名称:lambdaExpression

如何成功映射 AudioSummary

来源对象

enter image description here

目标对象 enter image description here

1 个答案:

答案 0 :(得分:2)

编辑:一般情况下,请尝试AutoMapper.Mapper.AssertConfigurationIsValid();,这会向您显示地图设置中的所有问题。

根据您提供的信息,您似乎还需要为AudioSummary类(目标和源)定义地图:

    [TestFixture]
    public class MappingTest
    {
        public class SourceAudioSummary
        {
            public int Id { get; set; }
            public string OtherData { get; set; }
        }

        public class TrackProfile
        {
            public string Whatever { get; set; }
            public SourceAudioSummary AudioSummary { get; set; }
        }

        public class DestAudioSummary
        {
            public int Id { get; set; }
            public string OtherData { get; set; }
        }

        public class Profile
        {
            public string Whatever { get; set; }
            public DestAudioSummary AudioSummary { get; set; }
        }

        [Test]
        public void Mapping()
        {
            Mapper.CreateMap<SourceAudioSummary, DestAudioSummary>();
            Mapper.CreateMap<TrackProfile, Profile>();

            var trackProfile = new TrackProfile
                {
                    Whatever = "something",
                    AudioSummary = new SourceAudioSummary
                        {
                            Id = 1,
                            OtherData = "other"
                        }
                };

            var profile = Mapper.Map<TrackProfile, Profile>(trackProfile);

            Assert.That(profile.Whatever == "something");
            Assert.That(profile.AudioSummary.Id == 1);
            Assert.That(profile.AudioSummary.OtherData == "other");
        }
    }