Mapster icon indicating copy to clipboard operation
Mapster copied to clipboard

Explicit mapping throws on mapping interface into model

Open tiger31 opened this issue 4 years ago • 1 comments

Code example (net6.0) Mapster version: 7.3.0

Program.cs

using ConsoleApp1;
using Mapster;
using MapsterMapper;

var config = TypeAdapterConfig.GlobalSettings.Clone();
config.RequireExplicitMapping = true;

config.ForType<IFooType, FooModel>()
    .Map(d => d.Foo, s => s.Foo);

var mapper = new Mapper(config);

var fooModel = mapper.Map<FooModel>(FooResolver.Resolve("bar"));

class FooModel
{
    public string Foo { get; set; }
}

FooResolver.cs

namespace ConsoleApp1
{
    public sealed class FooResolver
    {
        public static IFooType Resolve(string foo)
        {
            return new FooType
            {
                Foo = foo
            };
        }

        private class FooType : IFooType
        {
            public string Foo { get; set; }
        }
    }

    public interface IFooType
    {
        public string Foo { get; set; }
    }
}

I expect that on line 13 of Program.cs IFooType returned by FooResolver will be successfully mapped to FooModel but instead I'm getting exception

Unhandled exception. Mapster.CompileException: Error while compiling
source=ConsoleApp1.FooResolver+FooType
destination=FooModel
type=Map
 ---> System.InvalidOperationException: Implicit mapping is not allowed (check GlobalSettings.RequireExplicitMapping) and no configuration exists
   at Mapster.Adapters.BaseAdapter.CreateExpressionBody(Expression source, Expression destination, CompileArgument arg)
   at Mapster.Adapters.BaseAdapter.CreateAdaptFunc(CompileArgument arg)
   at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
   --- End of inner exception stack trace ---
   at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
   at Mapster.TypeAdapterConfig.CreateMapExpression(TypeTuple tuple, MapType mapType)
   at Mapster.TypeAdapterConfig.CreateDynamicMapExpression(TypeTuple tuple)
   at Mapster.TypeAdapterConfig.<GetDynamicMapFunction>b__66_0[TDestination](TypeTuple tuple)
   at Mapster.TypeAdapterConfig.<>c__DisplayClass55_0`1.<AddToHash>b__0(TypeTuple types)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Mapster.TypeAdapterConfig.AddToHash[T](ConcurrentDictionary`2 hash, TypeTuple key, Func`2 func)
   at Mapster.TypeAdapterConfig.GetDynamicMapFunction[TDestination](Type sourceType)
   at MapsterMapper.Mapper.Map[TDestination](Object source)
   at Program.<Main>$(String[] args) in D:\ConsoleApp1\ConsoleApp1\Program.cs:line 13

Do I misunderstand RequireExplicitMappin or is it a bug?

tiger31 avatar May 04 '22 12:05 tiger31

In order to identify issues that are still active, we are closing issues that we believe are either resolved or are dormant. If your issue is still active then please reopen. Thanks.

stagep avatar Jan 07 '25 18:01 stagep