使用内联选项更新现有实体并不起作用

时间:2017-12-06 14:32:32

标签: c# .net automapper

考虑以下代码:

 [TestMethod]
    public void AssertAutoMapper()
    {
        Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Entity, EntityModel>()
                    .ReverseMap();

                cfg.CreateMap<Message, MessageModel>()
                    .ReverseMap();
            }
        );

        Mapper.Configuration.AssertConfigurationIsValid();

        var model = new EntityModel() { Messages = new List<MessageModel>() {  } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity, opt => opt. ConfigureMap().ForMember(x => x.Messages, o => o.UseDestinationValue()));

        Assert.IsTrue(entity.Messages.Count == 1);
    }

我的第一个断言是好的,但第二个失败了。 我试过Ignore(),但我遇到了同样的问题。

1 个答案:

答案 0 :(得分:0)

我不确定为什么它不能像你那样工作,而是在初始化过程中进行配置。

        Mapper.Initialize(cfg =>
                {
                    cfg.CreateMap<Entity, EntityModel>()
                        .ReverseMap().ForMember(x => x.Messages, o => o.Ignore());
                    cfg.CreateMap<Message, MessageModel>()
                        .ReverseMap();
                });

        Mapper.Configuration.AssertConfigurationIsValid();

        var model = new EntityModel() { Messages = new List<MessageModel>() { } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity);
        Assert.IsTrue(entity.Messages.Count == 1);

修改

如果您已在Initialize方法中提供了配置,则内联配置无效。因此,要使其正常运行,您必须:

        Mapper.Initialize(cfg => { });
        Mapper.Configuration.AssertConfigurationIsValid();
        var model = new EntityModel() { Messages = new List<MessageModel>() { } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity, opt => opt.ConfigureMap().ForMember(x => x.Messages, o => o.Ignore()));