开发者

I loaded my database using automapper. Now how do I get the data back out and into the viewModel again?

So I have a 7 ViewModels that reference 3 domain models, I used automapper to map the Models to the ViewModels, That worked great, now I want to populate the ViewModel from data stored in the database and I'm running into alot of problems.

Here is my 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>();
}

How do I tell the application, "When I load from DBContext, move the entity into the ViewModel automatically", It seems like with Automapper you can load an entity f开发者_开发百科rom a ViewModel, but not the reverse.


Automapper can do the reverse, you just have to create the map for it:

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

As for loading mapping automatically at load time, I'm not aware of this functionality but it can be setup with a mapping helper to your linq query pretty easy:

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));
    }
}

Then in your query:

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


AutoMapper doesn't automatically define bi-directional mappings. If you want to map from your view model to the corresponding domain model you should define this mapping as well:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜