Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions src/Mapster.Tests/WhenPerTypeShallowCopyOverride.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using Mapster.Models;
using MapsterMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;

namespace Mapster.Tests
{
/// <summary>
/// https://github.com/MapsterMapper/Mapster/issues/938
/// </summary>
[TestClass]
public class WhenPerTypeShallowCopyOverride
{
[TestMethod]
public void GlobalShallowCopy_WithPerTypeDeepCopy_ShouldRestoreViaMapToTarget()
Copy link
Copy Markdown
Contributor

@DocSvartz DocSvartz May 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is not valid and fail ❌

To obtain the desired result, the issue author used an incorrect configuration.

This is what the author wanted to achieve.

[TestMethod]
public void GlobalShallowCopy_WithPerTypeDeepCopy_ShouldRestoreViaMapToTarget()
{
    var cfg = new TypeAdapterConfig();
    cfg.RequireExplicitMapping = true;
    cfg.Default.AvoidInlineMapping(true);

    cfg.NewConfig<RandomObject2, RandomObject2>();
    cfg.NewConfig<RandomObject1, RandomObject1>()
        .Include<RandomObject2, RandomObject2>();

    cfg.NewConfig<MyFailStuff, MyFailStuff>()
       // .ShallowCopyForSameType(true)
        .UseDestinationValue(x => x.Item1)
        .UseDestinationValue(x => x.Item2);



    cfg.Compile();

    var mapper = new Mapper(cfg);


   

    var dynamicStuff = new MyFailStuff();
    dynamicStuff.Item1 = new RandomObject1();
    dynamicStuff.Item1.SampleName = "SN1";
    dynamicStuff.Item2 = new RandomObject2() { SampleNumber = 2 };
    //dynamicStuff.Item2.SampleNumber = 2;

    var str = dynamicStuff.BuildAdapter(cfg).CreateMapToTargetExpression<MyFailStuff>();



    var originalStuff = mapper.Map<MyFailStuff, MyFailStuff>(dynamicStuff);

    dynamicStuff.Item1.SampleName = "SN1CHANGED";
    (dynamicStuff.Item2 as RandomObject2).SampleNumber = 3;

    mapper.Map(originalStuff, dynamicStuff);

    dynamicStuff.Item1.SampleName.ShouldBe("SN1");
    (dynamicStuff.Item2 as RandomObject2).SampleNumber.ShouldBe(2);
    ReferenceEquals(dynamicStuff.Item1, originalStuff.Item1).ShouldBeFalse();
    ReferenceEquals(dynamicStuff.Item2, originalStuff.Item2).ShouldBeFalse();
}

  public class RandomObject1
  {
      public string? SampleName { get; set; }
  }

  public class RandomObject2 : RandomObject1
  {
      public int SampleNumber { get; set; }
  }

{
var cfg = new TypeAdapterConfig();
cfg.RequireExplicitMapping = true;
cfg.Default.ShallowCopyForSameType(true);
cfg.Default.AvoidInlineMapping(true);

cfg.NewConfig<RandomObject2, RandomObject2>();
cfg.NewConfig<RandomObject1, RandomObject1>();

cfg.NewConfig<MyFailStuff, MyFailStuff>()
.ShallowCopyForSameType(false);

cfg.GetMergedSettings(new TypeTuple(typeof(MyFailStuff), typeof(MyFailStuff)), MapType.Map)
.ShallowCopyForSameType.ShouldBe(false);

cfg.Compile();

var mapper = new Mapper(cfg);

var dynamicStuff = new MyFailStuff();
dynamicStuff.Item1 = new RandomObject1();
dynamicStuff.Item1.SampleName = "SN1";
dynamicStuff.Item2 = new RandomObject2();
dynamicStuff.Item2.SampleNumber = 2;

var originalStuff = mapper.Map<MyFailStuff, MyFailStuff>(dynamicStuff);

dynamicStuff.Item1.SampleName = "SN1CHANGED";
dynamicStuff.Item2.SampleNumber = 3;

mapper.Map(originalStuff, dynamicStuff);

dynamicStuff.Item1.SampleName.ShouldBe("SN1");
dynamicStuff.Item2.SampleNumber.ShouldBe(2);
ReferenceEquals(dynamicStuff.Item1, originalStuff.Item1).ShouldBeFalse();
ReferenceEquals(dynamicStuff.Item2, originalStuff.Item2).ShouldBeFalse();
}

[TestMethod]
public void ParentDeepCopyOverride_ShouldNotDisableImplicitNestedShallowCopyForSameType()
{
var cfg = new TypeAdapterConfig();
cfg.Default.ShallowCopyForSameType(true);
cfg.NewConfig<Container, Container>()
.ShallowCopyForSameType(false);

cfg.Compile();

var src = new Container { Child = new NestedChild { Value = 1 } };
var dest = src.Adapt<Container>(cfg);

ReferenceEquals(src.Child, dest.Child).ShouldBeTrue();
}

public class Container
{
public NestedChild? Child { get; set; }
}

public class NestedChild
{
public int Value { get; set; }
}

public class MyFailStuff
{
public MyFailStuff()
{
CreateEmptyEntities();
}

public void CreateEmptyEntities()
{
Item1 ??= new RandomObject1();
Item2 ??= new RandomObject2();
}

public RandomObject1? Item1 { get; set; }

public RandomObject2? Item2 { get; set; }
}

public class RandomObject1
{
public string? SampleName { get; set; }
}

public class RandomObject2
{
public int SampleNumber { get; set; }
}
}
}
11 changes: 10 additions & 1 deletion src/Mapster/Adapters/BaseAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,16 @@ internal Expression CreateAdaptExpression(Expression source, Type destinationTyp
var notUsingDestinationValue = mapping is not { UseDestinationValue: true };
Expression exp;

if (_source.Type == destinationType && arg.Settings.ShallowCopyForSameType == true
var shallowCopySettings = arg.Settings;
if (_source.Type == destinationType)
{
if (arg.Context.Config.RuleMap.ContainsKey(tuple))
shallowCopySettings = arg.Context.Config.GetMergedSettings(tuple, arg.MapType);
else if (arg.Settings.ShallowCopyForSameType != true)
shallowCopySettings = arg.Context.Config.GetMergedSettings(tuple, arg.MapType);
}

if (_source.Type == destinationType && shallowCopySettings.ShallowCopyForSameType == true
&& notUsingDestinationValue && rule == null)
exp = _source;
Comment on lines +515 to 517
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the wrong level of mapping.
This is where properties are mapped, not types.

A shallow copy creates a new top-level object but does not duplicate nested elements. Instead, it copies the memory references of nested objects and arrays. This means modifying a nested property in the copy will inadvertently change it in the original object.

If you consider this a new TopLevel, a new object must be created here in any case, and its properties must be copied by reference.
Or if this is a parsing of the properties of the original TopLevel (the one specified in arg).
Then searching for this setting is pointless, since all TopLevel properties must be copied by reference in any case.

else if (source is ConditionalExpression cond && mapping != null)
Expand Down