1

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

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

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

Mapper.CreateMap<WordViewModel, Word>();

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

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

4

1 回答 1

3

You should only create the maps once during Application_Start and not use Reset. For example:

Global.axac.cs

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

AutoMapper Configuration

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

Make sure you include a unit test to validate your mappings:

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

Then just call the Mapper.Map as required in your application.

于 2013-01-29T03:02:30.517 回答