Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling derived classes more elegant #104

Closed
ramondeklein opened this issue Mar 10, 2017 · 1 comment
Closed

Handling derived classes more elegant #104

ramondeklein opened this issue Mar 10, 2017 · 1 comment

Comments

@ramondeklein
Copy link

Assume I have the following class structure and I want to be able to map between the two:

public class Base1
public class DerivedA1 : Base1
public class DerivedB1 : Base1

public class Base2
public class DerivedA2 : Base2
public class DerivedB2 : Base2

I have to create two functions to map between the two:

static Base2 Map1to2(Base1 base1)
{
    if (base1 is DerivedA1)
        return ((DerivedA1)base1).Adapt<DerivedA2>();
    if (base1 is DerivedB1)
        return ((DerivedB1)base1).Adapt<DerivedB2>();
    return base1.Adapt<Base2>();
}

static Base1 Map2to1(Base2 base2)
{
    if (base2 is DerivedA2)
        return ((DerivedA2)base2).Adapt<DerivedA1>();
    if (base2 is DerivedB2)
        return ((DerivedB2)base2).Adapt<DerivedB1>();
    return base2.Adapt<Base1>();
}

And I need to setup these mappers:

var config = new TypeAdapterConfig();
config.ForType<Base1, Base2>().ConstructUsing(src => Map1to2(src));
config.ForType<Base2, Base1>().ConstructUsing(src => Map2to1(src));
var adapter = new Adapter(config);

Using this approach I can use adapter.Adapt<Base2>(derivedB1) and still get an instance of DerivedB2.

It would be much more elegant that we don't require such additional methods, but to use the same kind of syntax that AutoMapper is using:

config.ForType<Base1, Base2>().Include<DerivedA1, DerivedA2>().Include<DerivedB1, DerivedB2>();
config.ForType<Base2, Base1>().Include<DerivedA2, DerivedA1>().Include<DerivedB2, DerivedB1>();

I have found the Inherits method, but it doesn't seem to work for this scenario.

@chaowlert
Copy link
Collaborator

Hi, I added Include command in Mapster 3.0 (https://github.com/chaowlert/Mapster/wiki/Config-inheritance), please try. Thx u.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants