我是AutoMapper工具的新手,到目前为止,这是一个令人惊奇的工具。在映射模型内部的集合和相应的ViewModel对象时,我遇到了困难。
为了简单起见,我修改了代码:
型号:
public class VoteQuestion
{
public virtual ICollection<VoteAnswerOption> VoteAnswerOptions { get; set; }
}相应的ViewModel:
public class CreateVoteQuestionViewModel
{
public List<VoteAnswerOptionViewModel> PossibleAnswers { get; set; }
}另一种模式:
public class VoteAnswerOption
{
public string Answer { get; set; }
}以及相应的ViewModel:
public class VoteAnswerOptionViewModel
{
public string Answer { get; set; }
}我的Mapper在“Startup.cs”中的设置。尝试了几个选项,除了映射集合之外,它对其他一切都有效。
Mapper.Initialize(config =>
{
config.CreateMap<VoteAnswerOption, VoteAnswerOptionViewModel>().ReverseMap();
config.CreateMap<List<VoteAnswerOptionViewModel>, ICollection<VoteAnswerOption>>().ReverseMap();
config.CreateMap<VoteQuestion, CreateVoteQuestionViewModel>()
.ForMember(dest => dest.PossibleAnswers, opts => opts.MapFrom(src => src.VoteAnswerOptions))
.ForMember(dest=>dest.PossibleAnswers,opts=>opts.MapFrom(src=>Mapper.Map<ICollection<VoteAnswerOption>, List<VoteAnswerOptionViewModel>>(src.VoteAnswerOptions)))
.ReverseMap();
});最后,我的Controller操作中的映射:
var newQuestion = Mapper.Map<CreateVoteQuestionViewModel, VoteQuestion>(voteQuestion);我遗漏了什么?
发布于 2016-12-20 17:24:38
这个测试通过了:请注意,只有在映射简单且不包含任何ReverseMap()调用的情况下,才能使用ForMember。
public class VoteQuestion {
public virtual ICollection<VoteAnswerOption> VoteAnswerOptions { get; set; }
}
public class CreateVoteQuestionViewModel {
public List<VoteAnswerOptionViewModel> PossibleAnswers { get; set; }
}
public class VoteAnswerOption {
public string Answer { get; set; }
}
public class VoteAnswerOptionViewModel {
public string Answer { get; set; }
}
[TestFixture]
public class SOTests {
[Test]
public void Test_41247396() {
Mapper.Initialize(config => {
config.CreateMap<VoteAnswerOption, VoteAnswerOptionViewModel>().ReverseMap();
config.CreateMap<VoteQuestion, CreateVoteQuestionViewModel>()
.ForMember(dest => dest.PossibleAnswers,
opts => opts.MapFrom(src => src.VoteAnswerOptions));
config.CreateMap<CreateVoteQuestionViewModel, VoteQuestion>()
.ForMember(dest => dest.VoteAnswerOptions,
opts => opts.MapFrom(src => src.PossibleAnswers));
});
var voteQuestion = new VoteQuestion {
VoteAnswerOptions = new List<VoteAnswerOption> {
new VoteAnswerOption { Answer = "Correct" }
}
};
var newQuestion = Mapper.Map<VoteQuestion, CreateVoteQuestionViewModel>(voteQuestion);
newQuestion.PossibleAnswers.Count.Should().Be(1);
newQuestion.PossibleAnswers.Single().Answer.Should().Be("Correct");
var vm = new CreateVoteQuestionViewModel {
PossibleAnswers = new List<VoteAnswerOptionViewModel> {
new VoteAnswerOptionViewModel {Answer = "Spot on"}
}
};
var q = Mapper.Map<CreateVoteQuestionViewModel, VoteQuestion>(vm);
q.VoteAnswerOptions.Count.Should().Be(1);
q.VoteAnswerOptions.Single().Answer.Should().Be("Spot on");
}
}https://stackoverflow.com/questions/41247396
复制相似问题