Search code examples
c#.netrepositoryautomapper

AutoMapper.Map ignore all Null value properties from source object


I'm trying to map 2 objects of the same type. What I want to do is AutoMapper to igonore all the properties, that have Null value in the source object, and keep the existing value in the destination object.

I've tried using this in my "Repository", but it doesn't seem to work.

Mapper.CreateMap<TEntity, TEntity>().ForAllMembers(p => p.Condition(c => !c.IsSourceValueNull));

What might be the problem ?


Solution

  • Interesting, but your original attempt should be the way to go. Below test is green:

    using AutoMapper;
    using NUnit.Framework;
    
    namespace Tests.UI
    {
        [TestFixture]
        class AutomapperTests
        {
    
          public class Person
            {
                public string FirstName { get; set; }
                public string LastName { get; set; }
                public int? Foo { get; set; }
            }
    
            [Test]
            public void TestNullIgnore()
            {
                Mapper.CreateMap<Person, Person>()
                        .ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));
    
                var sourcePerson = new Person
                {
                    FirstName = "Bill",
                    LastName = "Gates",
                    Foo = null
                };
                var destinationPerson = new Person
                {
                    FirstName = "",
                    LastName = "",
                    Foo = 1
                };
                Mapper.Map(sourcePerson, destinationPerson);
    
                Assert.That(destinationPerson,Is.Not.Null);
                Assert.That(destinationPerson.Foo,Is.EqualTo(1));
            }
        }
    }