MapsterMapper / Mapster

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

Adapt/AdaptToType DOES NOT working with anonymous object that returned from method #697

Open tungnt-hemera opened 6 months ago

tungnt-hemera commented 6 months ago
using Mapster;
using MapsterMapper;

var foo = new Foo(1, 2);
var t = foo.Get();

// var bar = t.Adapt<Bar>(); // <== Failed: '<>f__AnonymousType0<int,int>' does not contain a definition for 'Adapt'
// var bar = t.BuildAdapter().AdaptToType<Bar>(); // <== Failed '<>f__AnonymousType0<int,int>' does not contain a definition for 'BuildAdapter'

var mapper = new Mapper(TypeAdapterConfig.GlobalSettings);
var bar = mapper.Map<Bar>(t); // <== OK

// var t = new { A = 1, B = 2 }; 
// var bar = t.Adapt<Bar>(); //  <== Failed: '<>f__AnonymousType0<int,int>' does not contain a definition for 'Adapt'
// var bar = t.BuildAdapter().AdaptToType<Bar>(); // <== OK

Console.WriteLine($"A = {bar.A}; B = {bar.B}");

public class Foo
{
    private int a;
    private int b;
    public Foo(int a, int b)
    {
        this.a = a;
        this.b = b;
    }
    public dynamic Get()
    {
        return new { A = a, B = b };
    }
}

public class Bar
{
    public int A { get; set; }
    public int B { get; set; }
}

But IMapper works. Why?