I'm new to AutoMapper and, unless I'm misunderstanding, AutoMapper should always create deep copies when mapping to a Dto. Yet, the following test code is showing me that it's creating shallow copies. What am I missing here?
Mapping Config
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 Dto Setup
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 modifying homeDto's Abba value to 33, home's Abba value also changes to 33. Did I misconfigure something? What do I have to do to fix this?
You're reusing a type on both the source and destination objects, "MyStuff". When AutoMapper sees two assignable types, it assigns them rather than copying them. You can override this behavior by creating an explicit map:
Mapper.CreateMap<MyStuff, MyStuff>();
AutoMapper defaults to assigning, as AutoMapper is not a copying/cloning library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With