复杂结构之间的自动映射

时间:2017-03-22 02:46:03

标签: automapper

我是asp.net核心项目中的AutoMapper。 我需要将ProjectStructure映射到Job。 这是我的课程。任何帮助将不胜感激。 我无法从文件中找出答案

package db.migration;

import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;

public class V2_1__Add_Users implements SpringJdbcMigration {
    public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
        jdbcTemplate.execute("INSERT INTO users (email, password) VALUES ('test@test.com', 'test123')");
    }
}

2 个答案:

答案 0 :(得分:1)

您可以创建一个AutomapperConfiguration类:

public class AutoMapperConfiguration
{
    public void Initialize()
    {
        AutoMapper.Mapper.Initialize((config) =>
        {
            config.CreateMap<ProjectStructure, Job>()
                  .AfterMap((src, dest) => 
                            {
                                dest.JobID = src.JobInformationID;
                                dest.Addresses = new List<Address>
                                {
                                    new Address
                                    {
                                        StreetNumber = src.CustomerInformation.ContactDetails.StreetNo,
                                        UnitNumber = src.CustomerInformation.ContactDetails.UnitNo
                                    }
                                };
                            });
        });
    }
}

然后在你的启动类中调用AutoMapperConfiguration.Initialize();方法(无论是什么)

答案 1 :(得分:0)

我有另外一个像这样定义的地图

    CreateMap<ContactDetail, address>()
            .ForMember(m => m.city, opt => opt.MapFrom(cd => cd.SuburbAddress))
            .ForMember(m => m.streetNumber, opt => opt.MapFrom(cd => cd.StreetNo))
            .ForMember(m => m.street, opt => opt.MapFrom(cd => cd.StreetAddress))
            .ForMember(m => m.town, opt => opt.MapFrom(cd => cd.SuburbAddress))
            .ForMember(m => m.unitNumber, opt => opt.MapFrom(cd => cd.UnitNo))
            .AfterMap((ContactDetail, address) => { address.contactType = "Site"; address.tvStart = DateTime.Today; });

如何在.AfterMap中使用它而不是映射每个属性?