我需要你的帮助。我对automapper有基本的经验,一切都很好,但无论如何,我无法将源对象中的下一个更改映射到目标对象。
让我稍微解释一下:
在IUser中,我添加了一个属性"UserDetails",这个类包含一个名为"Domains"的Guid属性列表。
我想将第二级列表属性映射到我的UserDto对象,其中guid属性的列表位于第一级。在下面的示例中,Userkey映射工作正常,但我一直为"DomainIds"获取null,没有发现我做错了什么。我希望你能帮我
public interface IUser
{
UserKey Key { get; }
UserDetails Details { get; set; }
FirstName { get; }
}
public struct UserKey
{
private readonly Guid _id;
public UserKey(Guid id)
{
_id = id;
}
}
public class UserDetails
{
public List<Guid> Domains { get; set; }
}
public class UserDto
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public List<Guid> DomainIds { get; set; }
}
映射设置如下:
CreateMap<IUser, UserDto>()
.ForMember(
dest => dest.Id,
opt => opt.MapFrom(src => src.Key.Id))
.ForMember(
dest => dest.DomainIds,
opt => opt.MapFrom(src => src.Details.Domains))
在我的测试中,我像这样映射用户(它是一个IUser(。Fyi,所有其他属性都映射精细
_mapper.Map<UserDto>(user);
您的映射对我来说似乎很好:
Mapper.Initialize(config =>
{
config.CreateMap<User, UserDto>()
.ForMember(
dest => dest.Id,
opt => opt.MapFrom(src => src.Key.Id))
.ForMember(
dest => dest.DomainIds,
opt => opt.MapFrom(src => src.Details.Domains));
});
var user = new User
{
FirstName = "foo",
Key = new UserKey { Id = Guid.NewGuid() },
Details = new UserDetails
{
Domains = new List<Guid> { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() },
},
};
var result = Mapper.Map<UserDto>(user);
使用以下类型:
public class User
{
public UserKey Key { get; set; }
public UserDetails Details { get; set; }
public string FirstName { get; set; }
}
public class UserKey
{
public Guid Id {get;set;}
}
public class UserDetails
{
public List<Guid> Domains { get; set; }
}
public class UserDto
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public List<Guid> DomainIds { get; set; }
}