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 ?
So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.
The Null substitution allows us to supply an alternate value for a destination member if the source value is null. That means instead of mapping the null value from the source object, it will map from the value we supply.
By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.
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)); } } }
Condition
overload with 3 parameters let's you make expression equivalent to your example p.Condition(c => !c.IsSourceValueNull)
:
Method signature:
void Condition(Func<TSource, TDestination, TMember, bool> condition
Equivalent expression:
CreateMap<TSource, TDestination>.ForAllMembers( opt => opt.Condition((src, dest, sourceMember) => sourceMember != null));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With