更新后需要AutoMapper.Reset()

时间:2013-01-27 11:38:38

标签: asp.net-mvc-4 automapper

我在MVC应用程序中使用AutoMapper。 在GET中,我需要显示一个对象列表并将它们映射为:

Mapper.CreateMap<Word, WordViewModel>();
Mapper.Map<IList<Word>, IList<WordViewModel>>(list);

然后,用户可以编辑并保存,在POST中我执行以下操作

Mapper.CreateMap<WordViewModel, Word>();

一切都好。但是当我试图再次获取列表时,AutoMapper说它无法正确执行映射。

一旦我不再需要它,我就解决了调用AutoMapper.Reset()的问题。但我不确定这是正确的工作流程。

1 个答案:

答案 0 :(得分:3)

您应该只在Application_Start期间创建一次地图,而不是使用Reset。例如:

<强> Global.axac.cs

protected void Application_Start()
{
    Mapper.Initialize(x => x.AddProfile<ViewProfile>());
}

AutoMapper配置

public class ViewProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<Word, WordViewModel>();
        Mapper.CreateMap<WordViewModel, Word>();
    }
}

确保包含单元测试以验证映射:

[TestFixture]
public class MappingTests
{
    [Test]
    public void AutoMapper_Configuration_IsValid()
    {
        Mapper.Initialize(m => m.AddProfile<ViewProfile>());
        Mapper.AssertConfigurationIsValid();
    }
}

然后根据您的申请中的要求调用Mapper.Map