Reputation: 235
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));
});
Upvotes: 1
Views: 932
Reputation: 5194
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
Upvotes: 1
Reputation: 76
Try this
cfg.CreateMap<Person, Employee>() .ForMember(e => e.Address, p => p.MapFrom(a => new Address{Address1=a.Address1, Address2=a.Address2 }) });
Upvotes: 1