ServiceStack / Issues

Issue Tracker for the commercial versions of ServiceStack
11 stars 6 forks source link

ServiceStack AutoMapper creates new instances at Populate #707

Closed malibay81 closed 4 years ago

malibay81 commented 4 years ago

I have a problem with the AutoMapper. Defined is the class 'User', which has a reference to the class 'Car'. Defined is a 2nd class 'User2', which has a reference to the class 'Car2'. However, Car2 has an additional property 'Color'. A new instance is created by 'User' and 'User2'. The property 'Color' in 'Car2' was set to red. After mapping from 'User' to 'User2' the preset color in the 'Color' property of 'Car2' is zero. This will probably create a new instance of 'Car2' instead of using the existing ones.

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Car Car { get; set; }
}
public class User2
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Car2 Car { get; set; }
}
public class Car
{
    public string Name { get; set; }
    public int Age { get; set; }
}
public class Car2
{
    public string Name  { get; set; }
    public int Age { get; set; }
    public string Color { get; set; }
}

This test is okay

[TestMethod]
public void Does_populate ()
{
    var user = new User {FirstName = "Demis", LastName = "Bellot", Car = new Car {Name = "BMW X6", Age = 3}};
    var userDto = new User ().PopulateWith (user);

    Assert.AreEqual (userDto.FirstName, user.FirstName);
    Assert.AreEqual (userDto.LastName, user.LastName);
    Assert.AreEqual (userDto.Car.Name, user.Car.Name);
    Assert.AreEqual (userDto.Car.Age, user.Car.Age);
}

This test fails

[TestMethod]
public void Does_populate2 ()
{
    var user  = new User {FirstName = "Demis", LastName = "Bellot", Car = new Car {Name = "BMW X6", Age = 3}};
    var user2 = new User2 {Car = new Car2 {Color = "Red"}};
    user2.PopulateWith (user);

    Assert.AreEqual (user2.FirstName, user.FirstName);
    Assert.AreEqual (user2.LastName, user.LastName);
    Assert.AreEqual (user2.Car.Name, user.Car.Name);
    Assert.AreEqual (user2.Car.Age, user.Car.Age);
    **Assert.AreEqual ("Red", user2.Car.Color);**
}
mythz commented 4 years ago

That's the expected behavior, it overwrites the Car property, it doesn't merge them.