Mapster icon indicating copy to clipboard operation
Mapster copied to clipboard

New instance created when mapping via `Adapt` existing "child" object with public ctor with parameters

Open gurustron opened this issue 11 months ago • 5 comments

// Source
public class EditModelCommand
{
    public string Name { get; set; }
    public EditModelChild Child { get; set; }
}

public class EditModelChild
{
    public int Property1 { get; set; }
}

// Destination 
public class Model
{
    public string Name { get; set; }
    public Child Child { get; set; }
}

public class Child
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }

    private Child()
    {
        Debug.WriteLine("new Child");
    }

    public Child(int property1, int property2)
    {
        Debug.WriteLine($"new Child({property1}, {property2})");
        Property1 = property1;
        Property2 = property2;
    }
}

Mapping test:

[Fact]
public void Test()
{
    Model model = new()
    {
        Name = "Model",
        Child = new Child(10, 20)
    };
    EditModelCommand command1 = new()
    {
        Name = "Edited Model",
        Child = new EditModelChild()
        {
            Property1 = 99,
        }
    };
    EditModelCommand command = command1;

    var modelChild = model.Child;

    // ACT
    command.Adapt(model);

    // ASSERT
    Assert.Equal("Edited Model", model.Name);
    Assert.True(object.ReferenceEquals(modelChild, model.Child));
    Assert.Equal(99, model.Child.Property1);
    Assert.Equal(20, model.Child.Property2);
}

Which fails on the assertion.

Removing public Child(int property1, int property2) or changing it's visibility to private (or making parameterless one private Child() public) makes the test pass

gurustron avatar Feb 05 '25 12:02 gurustron

@gurustron Please indicate your Mapster version Check on latest pre-release?

linked #537 should be resolved in the latest pre-release (record detection)

DocSvartz avatar Feb 05 '25 12:02 DocSvartz

@DocSvartz

Thank you for the reply!

I was running tests with 7.4.1-pre01. It seems that 7.4.2-pre02 does not have the problem

gurustron avatar Feb 05 '25 14:02 gurustron

Confirmed that 7.4.2-pre02 does not have the problem. But the "downside" is the need of .Net 8

daaa57150 avatar Feb 05 '25 15:02 daaa57150

@daaa57150 What is the minimum Net target you need?

@andrerav What do you think about this?

Confirmed that 7.4.2-pre02 does not have the problem. But the "downside" is the need of .Net 8

DocSvartz avatar Feb 05 '25 16:02 DocSvartz

We are on a somewhat old project now, still using .net 6.0. I know we should update but it's not that easy for us (small team & the project contains stuff tightly coupled with .net 6.0)

daaa57150 avatar Feb 05 '25 17:02 daaa57150