Easy way to map two objects into one
The two objects:
-
The objects
internal class TargetPerson { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } // Ignore this property! [IgnoreProperty] public string IgnoreValue { get; set; } public int? OtherId { get; set; } } internal class SourcePerson { public int? Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string IgnoreValue { get; set; } public int OtherId { get; set; } }
-
Map two objects (both objects exists)
var sourcePerson = new SourcePerson { Id = null, FirstName = "Bender", LastName = "Rodriguez", IgnoreValue = "Some fancy value", OtherId = 666 }; var targetPerson = new TargetPerson(); Mapper.Map(sourcePerson, targetPerson);
-
Map two objects but create a new target object
var sourcePerson = new SourcePerson { Id = null, FirstName = "Bender", LastName = "Rodriguez", IgnoreValue = "Some fancy value", OtherId = 666 }; var targetPerson = Mapper.CreateAndMap<SourcePerson, TargetPerson>(sourcePerson);
-
The objects
var firstPerson = new TargetPerson { Id = 1, FirstName = "Bender", LastName = "Rodriguez", IgnoreValue = "Some fancy value", OtherId = 666 }; var secondPerson = new TargetPerson { Id = 1, FirstName = "Philip J.", LastName = "Fry", IgnoreValue = "Some fancy value", OtherId = 123 };
-
Get the changes
var changes = firstPerson.GetChanges(secondPerson);
The variable
change
contains a list with all changes. Every entry contains the following properties:- Property: The name of the property
- OldValue The "original" old value
- NewValue The "new" value
-
The result
+-----------+-----------+-----------+ | Property | OldValue | NewValue | +-----------+-----------+-----------+ | FirstName | Bender | Philip J. | | LastName | Rodriguez | Fry | | OtherId | 666 | 123 | +-----------+-----------+-----------+