Why is AutoMapper making small copies?

I'm new to AutoMapper, and if I'm not mistaken, AutoMapper should always create deep copies when matching with Dto. However, the following test code shows me that it creates small copies. What am I missing here?

Display configuration

using System; using System.Collections.Generic; using System.Linq; using System.Web; using AutoMapper; using Sandbox.Models; namespace Sandbox.Core.Automapper { public static class AutoMapperWebConfiguration { public static void Configure() { ConfigureUserMapping(); } private static void ConfigureUserMapping() { Mapper.CreateMap<Home, HomeDto>(); } } } 

Model and setup Dto

 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Sandbox.Models { public class Home { public int Price { get; set; } public int Price2 { get; set; } public MyStuff Stuff{ get; set; } } public class HomeDto { public int Price { get; set; } public int Price2 { get; set; } public MyStuff Stuff{ get; set; } } public class MyStuff { public int Abba { get; set; } } } 

Test code

 var home = new Home(); home.Stuff= new MyStuff(){Abba = 1}; var homeDto = Mapper.Map<HomeDto>(home); homeDto.MyStuff.Abba = 33; 

After changing the homeDto Abba value to 33, the value for the Abba home will also change to 33. Am I misunderstood something? What do I need to do to fix this?

+6
source share
1 answer

You reuse the type for both the source and target, "MyStuff". When AutoMapper sees two assignable types, it assigns them, not copies them. You can override this behavior by creating an explicit map:

 Mapper.CreateMap<MyStuff, MyStuff>(); 

Automapper assigns by default, since AutoMapper is not a copy / clone library.

+2
source

All Articles