我使用automapper加载了我的数据库。现在我如何将数据重新输出并再次进入viewModel?

时间:2011-06-29 14:18:46

标签: asp.net-mvc-3 automapper

所以我有一个7个ViewModel引用3个域模型,我使用了者自动将模型映射到ViewModels,这很好用,现在我想从存储在数据库中的数据中填充ViewModel而且我遇到了很多问题。

这是我的Automapper.Configure()

protected override void Configure()
{
    //Configure dynamically at save time.
    CreateMap<Step0ViewModel,Preparer>();
    CreateMap<Step1ViewModel, BusinessInformation>();
    CreateMap<Step2ViewModel, dr405>();
    CreateMap<Step3ViewModel, dr405>();
    CreateMap<Step4ViewModel, dr405>();
    CreateMap<Step5ViewModel, dr405>();
    CreateMap<Step6ViewModel, dr405>();
}

如何告诉应用程序,“当我从DBContext加载时,将实体自动移动到ViewModel”,似乎使用Automapper,您可以从ViewModel加载实体,但不能反过来。

2 个答案:

答案 0 :(得分:2)

AutoMapper不会自动定义双向映射。如果要从视图模型映射到相应的域模型,还应定义此映射:

CreateMap<Step0ViewModel, Preparer>();
CreateMap<Preparer, Step0ViewModel>();

答案 1 :(得分:2)

Automapper可以反过来,你只需要为它创建地图:

protected override void Configure()
{
    //Configure dynamically at save time.
    CreateMap<Preparer, Step0ViewModel>();
    ...
}

至于在加载时自动加载映射,我不知道这个功能,但可以使用映射助手设置你的linq查询非常简单:

public static class AutoMapperExtensions
{
    public static TResult MapTo<TResult>(this object self)
    {
        if (self == null)
            throw new ArgumentNullException();

        return (TResult)Mapper.Map(self, self.GetType(), typeof(TResult));
    }
}

然后在你的查询中:

var viewModel = _myContext.Preparers.Find(1).MapTo<Step0ViewModel>();