简体   繁体   中英

Mapping entity with AutoMapper

I am trying to map two entity using auto mapper(ver 6.1.1.0)

Classes I am testing with

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Add1 { get; set; }
    public string Add2 { get; set; }
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }

}
   public class Entity
{
    public int Id { get; set; }
    public string Title { get; set; }
}

I want to map Person to Employee. I tried below but not sure how to get this working

private void MapperTest()
{
    Mapper.Initialize(cfg =>
    {
        cfg.CreateMap<Person, Employee>()
        .ForMember(e => e.Address,
                   p => p.MapFrom(a => a.Address1))
                });

    var person = new Person { Id = 100, FirstName = "Rob", LastName = "Wood", Add1="Address line 1",Add2 = "Address line 2" ,CountryId =100,Country="UK"};
}

Update, if the Address entity contains another entity as property I tried below

Mapper.Initialize(cfg => {

                cfg.CreateMap<Person, Address>()
              .ForMember(a => a.Address1, opt => opt.MapFrom(p => p.Add1))
              .ForMember(a => a.Address2, opt => opt.MapFrom(p => p.Add2));
                    cfg.CreateMap<Person, Employee>()
                            .ForMember(e => e.Address,
                                       opt => opt.MapFrom(p => p))
                            .ForMember(b => b.Address.Country,
                            opt => opt.MapFrom(br => br));
            });

This should work:

cfg.CreateMap<Person, Address>()
        .ForMember(a => a.Address1, opt => opt.MapFrom(p => p.Add1))
        .ForMember(a => a.Address2, opt => opt.MapFrom(p => p.Add2));
cfg.CreateMap<Person, Employee>()
        .ForMember(e => e.Address,
                   opt => opt.MapFrom(p => p));

Short explanation: You split the mapping from Person to 2 entities and tell the mapper that Address is a child of Employee

尝试这个

cfg.CreateMap<Person, Employee>()  .ForMember(e => e.Address, p => p.MapFrom(a => new Address{Address1=a.Address1, Address2=a.Address2 }) });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM