Automapper bind automatically property of property by concatenating property name<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Automapper bind automatically property of property by concatenating property name

Posted on: November 14, 2013

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.

[TestClass] 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; } }
[TestMethod] public void TestMethod1() { var c = new ClassA(); c.PropertyA.Id = 123; Mapper.CreateMap<ClassA, ClassB>(); var mapped = Mapper.Map<ClassA, ClassB>(c); Assert.AreEqual(c.PropertyA.Id,mapped.PropertyAId); Assert.AreEqual(c.PropertyA.Suffixe,mapped.PropertyASuffixe); Assert.IsNull(mapped.NotReallyTheSame); } }

AutoMapperSuccess 400x68

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.