Skip to content

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

Open
@gurustron

Description

@gurustron
// 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions