MapsterMapper / Mapster

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

Mapster.Tool ignores base interface types #660

Open ChasakisD opened 7 months ago

ChasakisD commented 7 months ago

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

DocSvartz commented 7 months ago

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);
    }
}
ChasakisD commented 7 months ago

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?