Automapper bind automatically property of property by concatenating property name

This title has a lot of properties, I know. Today, I’ll show you with a simple unit test that Automapper bind properties’ property automatically with their name. For example, a class that has a property called User that has by itself a property called FirstName and LastName, will auto-bind to MyMappedClass.UserFirstName and MyMappedClass.UserLastName.

public class UnitTest1
	public class ClassA
		public ClassA()
			this.PropertyA = new ClassAB();

		public ClassAB PropertyA { get; set; }

	public class ClassAB
		public int Id { get; set; }
		public string Suffixe { get; set; }
		public string NotTheSame { get; set; }

	public class ClassB
		public int PropertyAId { get; set; }
		public string PropertyASuffixe { get; set; }
		public string NotReallyTheSame { get; set; }

	public void TestMethod1()
		var c = new ClassA();
		c.PropertyA.Id = 123;
		Mapper.CreateMap<ClassA, ClassB>();
		var mapped = Mapper.Map<ClassA, ClassB>(c);


The code above show you this reality. The ClassA is mapped to ClassB. Class A doesn’t specify any Automapper configuration, just a single CreateMap without options. Nevertheless, Automapper is bright enough to bind Id and Suffixe from ClassA to ClassB. This is because the name of those properties are present in the mapped ClassB class with the concatenation of the two properties name.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.