Automapper property mapping failed by matching partial property name

I have two classes that are displayed. The source class has a DateTime property that maps to a target property of type long ( DateTime.Ticks ), respectively UpdateDt and UpdateDtTicks .

When I use Automapper to map these two classes, my UpdateDtTicks property automatically gets the value from the UpdateDt property, even if the property names do not match, and I have not explicitly set the mapping for this property.

Is Automapper automatically setting a property because property names differ only at the end? If not, then why is this happening because this is unexpected behavior.

See code below:

 static void Main(string[] args) { Configuration.Configure(); var person = new OrderDto { OrderId = 999, MyDate = new DateTime(2015, 1, 1, 4, 5, 6) }; var orderModel = Mapper.Map<OrderModel>(person); Console.WriteLine(new DateTime(orderModel.MyDateTicks.Value)); Console.ReadLine(); } public class OrderDto { public int OrderId { get; set; } public DateTime MyDate { get; set; } } public class OrderModel { public int OrderId { get; set; } public long? MyDateTicks { get; set; } } public class Configuration { public static void Configure() { Mapper.CreateMap<OrderDto, OrderModel>(); } } 

Result in the console:

enter image description here

And the watch:

enter image description here

+6
source share
1 answer

You start the AutoMapper smoothing function. Frome documentation :

When you configure a source / destination type pair in AutoMapper, the configurator attempts to map the properties and methods of the source type to the properties in the destination type. If for any property in the destination type the property, method or method with the prefix "Get" does not exist in the source type, AutoMapper splits the name of the destination member into separate words (according to PascalCase conventions) .

Thus, given the following example (from their docs abridged in my answer):

 public class Order { public Customer Customer { get; set; } } public class Customer { public string Name { get; set; } } public class OrderDto { public string CustomerName { get; set; } public decimal Total { get; set; } } Mapper.CreateMap<Order, OrderDto>(); var order = new Order { Customer = new Customer { Name = "John Doe" } }; OrderDto dto = Mapper.Map<Order, OrderDto>(order); 

The CustomerName property corresponds to the Customer.Name property in the order.

This is exactly the same as MyDateTicks matching MyDate.Ticks , which returns long as needed ...

+5
source

All Articles