AutoMapper / AutoMapper.Collection

AutoMapper support for updating existing collections by equivalency
MIT License
245 stars 59 forks source link

Nullable ID's throw exception #97

Closed JimmyHannon closed 6 years ago

JimmyHannon commented 6 years ago

When using nullable properties for the equivalency checks and mapping on existing object, a nullreference exception is thrown. I was expecting that if the ID is null it is not equal and the item with null id would be added to the collection.

To reproduce run this test:

[Fact]
        public void Should_Work_With_Null_Id()
        {
            Mapper.Reset();
            Mapper.Initialize(x =>
            {
                x.AddCollectionMappers();
                x.CreateMap<ThingWithStringIdDto, ThingWithStringId>().EqualityComparison((dto, entity) => dto.ID == entity.ID);
            });

            var original = new List<ThingWithStringId>
            {
                new ThingWithStringId { ID = "1", Title = "test0" },
                new ThingWithStringId { ID = "2", Title = "test2" },
            };

            var dtos = new List<ThingWithStringIdDto>
            {
                new ThingWithStringIdDto { ID = "1", Title = "test0" },
                new ThingWithStringIdDto { ID = "2", Title = "test2" },
                new ThingWithStringIdDto { Title = "test3" }
            };

            Mapper.Map(dtos, original);

            original.Should().HaveSameCount(dtos);
        }

These are the test classes:

public class ThingWithStringId
        {
            public string ID { get; set; }
            public string Title { get; set; }
            public override string ToString() { return Title; }
        }

        public class ThingWithStringIdDto
        {
            public string ID { get; set; }
            public string Title { get; set; }
        }

As i understand the code tries to create a hash of the properties but since it is null it throws an exception. Might be related to Add null check to avoid NRE #71

TylerCarlson1 commented 6 years ago

It's a duplicate of #71.