我们正在开发一个项目,其中包含一个由角色组成的用户,角色由更细粒度的函数组成,我们正在尝试将DTO的多对多关系映射到我们的Business Objects。以下是DTO的示例:
public class UserDto {
public Guid Id { get; set; }
public string Username { get; set; }
public virtual ICollection<UserRoleDto> UserRoles { get; set; }
}
public class UserRoleDto {
public virtual Guid UserId { get; set; }
public virtual UserDto User { get; set; }
public virtual Guid RoleId { get; set; }
public virtual RoleDto Role { get; set; }
}
public class RoleDto {
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RoleFunctionDto> RoleFunctions { get; set; }
public virtual ICollection<UserRoleDto> UserRoles { get; set; }
}
public class RoleFunctionDto{
public virtual Guid RoleId { get; set; }
public virtual RoleDto Role { get; set; }
public virtual Guid FunctionId { get; set; }
public virtual FunctionDto Function { get; set; }
}
public class FunctionDto {
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RoleFunctionDto> RoleFunctions { get; set; }
}
理想情况下,我们希望将加入的DTO抽象出业务层。类似的东西:
public class User {
public Guid Id { get; set; }
public string Username { get; set; }
public ICollection<Role> Roles { get; set; }
// This would be nice to pull from the child roles... but not a must
public ICollection<Function> Functions { get; set; }
}
public class Role {
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Function> Functions { get; set; }
}
public class Function {
public Guid Id { get; set; }
public String Name { get; set; }
}
我已经阅读了自动播放器文档,但我无法理解如何正确设置这些映射。
我希望能够从UserDto映射到User(并返回)并填充对象图。
所以如果我认为我可以通过以下方式获得业务对象映射:
Mapper.CreateMap<UserDto, User>()
.AfterMap((s, d) => {
// Create the mappings for the many-to-many like:
foreach(var roleDto in d.UserRoles)
{
// Do I call the Mapper.Map function here?
s.Roles.Add(Mapper.Map<Role>(roleDto));
}
// Then loop through the mapped functions in the roles to add them to Functions?
})
但是,这会在RoleDto映射时导致循环映射,并获取UserRoles集合吗?
我已经读过Automapper并不是很擅长破坏对象图,所以我该如何改变这个过程呢?只是做同样的事情,但相反,调用Mapper.Map?