Home > front end >  Different parent classes map different subclasses problem
Different parent classes map different subclasses problem

Time:12-02

Profile.cs

public class TestConfigProfile : Profile
{
    public TestConfigProfile()
    {
        CreateMap<BaseBO, BaseVO>();
        CreateMap<A_BO, A_VO>();
        CreateMap<SubBO1, SubVO1>();
    }

    public class A_BO
    {
        public BaseBO Sub { get; set; }
    }
    public class A_VO
    {
        public BaseVO Sub { get; set; }
    }

    public class BaseBO
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class BaseVO
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class SubBO1 : BaseBO
    {
        public int Size { get; set; }
    }
    public class SubVO1 : BaseVO
    {
        public int Size { get; set; }
    }
}

test code like this...

public void TestConvert()
    {
        TestConfigProfile.A_BO bo = new TestConfigProfile.A_BO();
        bo.Sub = new TestConfigProfile.SubBO1()
        {
            Id = 1,
            Name = "SubBO1",
            Size = 4421
        };

        TestConfigProfile.A_VO vo = _mapper.Map<TestConfigProfile.A_BO, TestConfigProfile.A_VO>(bo);
    }

The result is as follows, but it does not meet my expectations, how can I configure this? Also I don't want to use a parent class.

enter image description here

Successfully mapped to a subclass.

CodePudding user response:

With AutoMapper, mapping inheritance is opt-in.

Therefore, when you map from BaseBO to BaseVO, you need to include the derived mappings.

public TestConfigProfile()
{
    CreateMap<BaseBO, BaseVO>()
        .Include<SubBO1, SubVO1>(); // Include necessary derived mappings
    CreateMap<A_BO, A_VO>();
    CreateMap<SubBO1, SubVO1>();
}

See this working example.

  • Related