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 に答える