MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.3k stars 328 forks source link

Invalid mapping to exists class if source is object #524

Open heggi opened 1 year ago

heggi commented 1 year ago
public class Source
{
    public int X1 { get; set; }
}
public class Dest
{
    public int X1 { get; set; }
}

var source = new Source { X1 = 123 };
var dest = new Dest { X1 = 321 };
var dest1 = source.Adapt(dest);
Console.WriteLine($"{dest.X1} {dest1.X1} {dest.GetHashCode()} {dest1.GetHashCode()}");

result: 123 123 19575591 19575591, dest and dest1 are the same object

void somemap(object source)
{
    var dest = new Dest { X1 = 321 };
    var dest1 = source.Adapt(dest);

    Console.WriteLine($"{dest.X1} {dest1.X1} {dest.GetHashCode()} {dest1.GetHashCode()}");
}

var source = new Source { X1 = 123 };
somemap(source);

result: 321 123 32001227 19575591 dest not changed, dest1 is a new object.

Any ideas? Why if source is object, Adapt create a new instance of dest class?

andrerav commented 1 year ago

Possibly related to #485

DocSvartz commented 11 months ago

@andrerav @heggi

Typeof(TSource) always return Type as Object. Need use dynamic or Cast to Runtime Type before Adapt

What happens is this: Adapt this for Object -> TDistination -> TDistination

In this case use special overload from (it work) :

var dest1 = source.Adapt(dest, source.GetType(), dest.GetType());

But a new instance is when the TDistination is detection as Record #537

DocSvartz commented 11 months ago

@andrerav @heggi

I get fix it, but this Null propagation for primitive types broke down. By the end of the week this problem will most likely be resolved. :)

DocSvartz commented 11 months ago

Any ideas? Why if source is object, Adapt create a new instance of dest class?

This Adapt Source from object to type of TDestination == source.Adapt<TDestination>()

ObjectAdapter not created Update function

DocSvartz commented 11 months ago

Hello @heggi can you provide additional samples for testing? My fantasy is over, I can’t think of anything else that can be tested in this case :)

Hello, @andrerav fixing of this Issue ready for review #645 . I managed to finish it a little faster than the end of the week :)

andrerav commented 11 months ago

Thank you @DocSvartz, I will review it later today! :)