Automapper集合映射:如何确定对象是已更新还是已创建

时间:2019-10-28 13:09:52

标签: c# automapper

我有以下代码

        public class AAA
        {
            public int Id { get; set; }

        }

        public class BBB
        {
            public int Id { get; set; }

            public int UpdatedOrCreated { get; set; }
        }


        [TestMethod]
        public void MappingTest2()
        {

            var _mapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddCollectionMappers();

                cfg.CreateMap<AAA, BBB>(MemberList.Destination)
                .EqualityComparison((a, b) => a.Id == b.Id)
                .ForMember(dest => dest.Id, src => src.MapFrom(m => m.Id))
                .ForMember(dest => dest.UpdatedOrCreated, /* set value 2 for Updated or 3 for Created */)
                .ForAllOtherMembers(m => m.Ignore());
            });

            _mapperConfiguration.AssertConfigurationIsValid();
            var mapper = _mapperConfiguration.CreateMapper();

            var varin = new List<AAA>
            {
                new AAA
                {
                    Id = 1,

                },
                new AAA
                {
                    Id = 2,

                }
            };

            var varout = new List<BBB>
            {
                new BBB
                {
                    Id = 1,

                }
            };


            var ttt = mapper.Map(varin, varout);

            ttt.Should().HaveCount(2);

            ttt[0].Id.Should().Be(1);
            ttt[0].UpdatedOrCreated.Should().Be(2);

            ttt[1].Id.Should().Be(2);
            ttt[1].UpdatedOrCreated.Should().Be(3);
        }

我正在使用Automapper Collection扩展,并希望基于创建新对象或更新现有对象来设置字段“ UpdatedOrCreated”。 我还没有找到一种方法。

1 个答案:

答案 0 :(得分:0)

public class AAA
{
    public int Id { get; set; }
    public string ValueA { get; set; }
}

public class BBB
{
    public int UpdatedOrCreated { get; set; } = 2;
    public int Id { get; set; }
    public string ValueA { get; set; }
}

public class CustomList : List<BBB>
{
    public new void Add(BBB item)
    {
        item.UpdatedOrCreated = 3;
        base.Add(item);
    }
}
var varout = new CustomList
{
    new BBB
    {
        Id = 1,
        ValueA = "bang"
    }
};