Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 480
Marty Avatar asked Sep 20 '12 13:09

Marty


People also ask

How do I ignore source property AutoMapper?

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.

Does AutoMapper handle null?

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.

Does AutoMapper map private fields?

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.


2 Answers

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));         }     } } 
like image 79
Void Ray Avatar answered Oct 11 '22 20:10

Void Ray


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)); 
like image 41
Nenad Avatar answered Oct 11 '22 20:10

Nenad