To ignore all unmapped properties using Automapper in C# and VB.NET you can use the following snippet.

Sample C#

var testClassA = new TestclassA() {Name = "Testname", Title = "Testtitle"};
Mapper.CreateMap<TestclassA, TestclassB>().ForAllMembers(opt => opt.Ignore());
Mapper.CreateMap<TestclassA, TestclassB>().ForMember(source => source.Title, destination => destination.MapFrom(x => x.Title));

var testClassB = Mapper.Map<TestclassA, TestclassB>(testClassA);
Console.WriteLine(testClassB.Title); //prints out "Testtitle"
Console.WriteLine(testClassB.Name); //print nothing  (NULL)

Sample VB.NET

Dim testClassA = New TestclassA() With { _
	Key .Name = "Testname", _
	Key .Title = "Testtitle" _
}
Mapper.CreateMap(Of TestclassA, TestclassB)().ForAllMembers(Function(opt) opt.Ignore())
Mapper.CreateMap(Of TestclassA, TestclassB)().ForMember(Function(source) source.Title, Function(destination) destination.MapFrom(Function(x) x.Title))

Dim testClassB = Mapper.Map(Of TestclassA, TestclassB)(testClassA)
Console.WriteLine(testClassB.Title)
'prints out "Testtitle"
Console.WriteLine(testClassB.Name)
'print nothing  (NULL)

3 thought on “How to ignore all unmapped properties using Automapper in C# and VB.NET”

Leave a Reply