从 ViewModel 映射到 Domain Model 时是否使用了 ReverseMap?
public class CustomProfile : Profile
{
protected override void Configure()
{
// Mapper.CreateMap<Model, ViewModel>();
// Mapper.CreateMap<ViewModel, Model>();
Mapper.CreateMap<Model, ViewModel>().ReverseMap();
}
}
这工作得很好,并且可以毫无问题地映射所有内容。
[TestInitialize]
public void Initialize()
{
Mapper.Initialize(conf => conf.AddProfile(new CustomProfile()));
}
[TestMethod]
public void AssertConfiguration()
{
Mapper.AssertConfigurationIsValid();
}
[TestMethod]
public void Test()
{
var model = new Model()
{
ComplexTypes = new Collection<ComplexType>() { new ComplexType() { SomeOtherValue = 1 }, new ComplexType() { SomeOtherValue = 4 } },
SomeValue = 3
};
var viewModel = Mapper.Map<ViewModel>(model);
Assert.AreEqual(model.SomeValue, viewModel.SomeValue);
Assert.AreEqual(model.ComplexTypes.Count, viewModel.ComplexTypes.Count);
Assert.AreEqual(model.ComplexTypes.ElementAt(0), viewModel.ComplexTypes.ElementAt(0));
Assert.AreEqual(model.ComplexTypes.ElementAt(1), viewModel.ComplexTypes.ElementAt(1));
model = Mapper.Map<Model>(viewModel);
Assert.AreEqual(viewModel.SomeValue, model.SomeValue);
Assert.AreEqual(viewModel.ComplexTypes.Count, model.ComplexTypes.Count);
Assert.AreEqual(viewModel.ComplexTypes.ElementAt(0), model.ComplexTypes.ElementAt(0));
Assert.AreEqual(viewModel.ComplexTypes.ElementAt(1), model.ComplexTypes.ElementAt(1));
}