Mapster icon indicating copy to clipboard operation
Mapster copied to clipboard

Mapster.Tool ignores base interface types

Open ChasakisD opened this issue 2 years ago • 2 comments

I have the following mapping configuration:

[Mapper]
public interface IInterfaceMapper
{
    _ClassB MapTo(_ClassA cA);
}

public class InterfaceMappingRegister : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        config.NewConfig<_InterfaceA, _InterfaceB>()
            .Map(x => x.IdB, x => x.IdA);
    }
}

public interface _InterfaceA
{
    string IdA { get; set; }
}

public class _ClassA : _InterfaceA
{
    public string IdA { get; set; }
}

public interface _InterfaceB
{
    string IdB { get; set; }
}

public class _ClassB : _InterfaceB
{
    public string IdB { get; set; }
}

Mapster.Tool generates the following mapper:

public partial class InterfaceMapper : IInterfaceMapper
{
    public _ClassB MapTo(_ClassA p1)
    {
        return p1 == null ? null : new _ClassB() {};
    }
}

The mapper completely ignores the base interface properties IdA and IdB. Is there any workaround for this?

Mapster.Tool version: 8.4.0

ChasakisD avatar Nov 15 '23 16:11 ChasakisD

Hello @ChasakisD, It doesn't ignore them. You haven't configured a mapping for your classes. The interface is a contract (declaration of supported behavior). ClassA and ClassB these are not inheritors of interfaces, they implement them.

In your case it should look exactly like this.


[Mapper]
public interface IInterfaceMapper
{
    _ClassB MapTo(_InterfaceA cA);
}

public class InterfaceMappingRegister : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        config.NewConfig<_InterfaceA, _ClassB>()
            .Map(x => x.IdB, x => x.IdA);
    }
}

DocSvartz avatar Nov 18 '23 19:11 DocSvartz

Yeah, If I explicitly create a mapping between the interfaces and the classes, it will work! The question is that what happens in the case I described where you automatically have the implemented properties mapped using the config that exists on the interface. Is that something that you want to implement? Is that something that this library cannot provide?

ChasakisD avatar Nov 20 '23 15:11 ChasakisD