我有3个相关的表。 Employee,Relative,RelationTypeCatalog。关系是IX_Relatives_EmployeeId
和IX_Relatives_RelationTypeCatalogId
。我想要实现的是,当返回员工的亲属列表时,我希望字段“ Relationship”显示存储在“ RelationType”中的值,该值是RelationTypeCatalog类的属性。我是编码和自动映射的新手,我真的可以使用一些帮助和指导。我能够将“ Relationship”字段设置为null。这是一些代码
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string DNI { get; set; }
public ICollection<Relative> Relatives { get; set; }
}
public class Relative
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public Employee Employee { get; set; }
public int EmployeeId { get; set; }
public RelationTypeCatalog RelationTypeCatalog { get; set; }
public int RelationTypeCatalogId { get; set; }
}
public class RelationTypeCatalog
{
public int Id { get; set; }
public string RelationType { get; set; }
public ICollection<Relative> Relatives { get; set; }
}
public class RelativeToReturnDto
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Relationship { get; set; }
}
and here is the Automapper
public class AutoMapperProfiles : Profile
{
CreateMap<Relative, RelativeToReturnDto>()
.ForMember(dest => dest.Age,
opt => opt.MapFrom(src => src.DateOfBirth.CalculateAge()))
.ForMember(dest => dest.Relationship,
opt => opt.MapFrom(src => src.RelationTypeCatalog.RelationType));
}
这里是我得到的JSON响应。
{
"id": 1,
"name": "Camacho",
"age": 29,
"dni": "(865) 494-2026",
"relatives": [
{
"id": 3,
"name": "Diego",
"age": 15,
"relationship": null
}
}
我期望得到的是"relationship": "Espouse"
wich是“ RelationType”字段中的对应值
Rob指出问题似乎是由您的输入引起的,而不是由AutoMapper
引起的,如在下面的示例中,Relationship
被映射:
var mapper = new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfiles>()));
var relative = new Relative { RelationTypeCatalog = new RelationTypeCatalog { RelationType = "rel1" } };
var dto = mapper.Map<RelativeToReturnDto>(relative);
Debug.Assert(dto.Relationship == "rel1");