[英]Mapping entity with AutoMapper
I am trying to map two entity using auto mapper(ver 6.1.1.0)
我正在尝试使用
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 更新,如果Address实体包含另一个实体作为我在下面尝试过的属性
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
简短说明:您将映射从
Person
拆分为2个实体,并告诉映射器Address
是Employee
的子代
尝试这个
cfg.CreateMap<Person, Employee>() .ForMember(e => e.Address, p => p.MapFrom(a => new Address{Address1=a.Address1, Address2=a.Address2 }) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.