使用自动映射器在构造函数中映射对象 [英] Using automapper to map objects within constructor

查看:101
本文介绍了使用自动映射器在构造函数中映射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据模型,一个用于数据库,一个用于视图模型,例如

I have two data models, one for database and one for viewmodels like

public class ModelA{
    string name {get;set;}
}

public class ModelB{
    ModelA Parent;

    ModelB(ModelA parent){
        Parent = parent;
   }
}

与ViewModel模型相同

And the ViewModel Models are the same

public class ViewModelA{
    string name {get;set;}
}

public class ViewModelB{
    ViewModelA Parent;
    IMapper map;
    ViewModelB(ViewModelA parent, IMapper _map){
        Parent = parent;
        map = _map;
   }
}

我正在尝试让自动映射器在ViewModelB和Model B的参数内映射父对象.但是我尝试的所有方法都失败了,或者我只能(使用ConstructUsing)创建父对象的新实例,而不能在其中映射一个构造函数.

Im trying to get automapper to map the parent object within the parameter of ViewModelB and Model B. But everything I have tried is failing or I can only create new instances of the parent object (using ConstructUsing), not map the one in the constructor.

这是我目前的个人资料

public ModelBProfile:Profile{
     CreateMap<ModelB, ViewModelB>()
                    .ForMember(m => m.Parent, opt => opt.MapFrom(p => p.Parent));
}

我一直在使用一个统一的容器以及WPF和Prism.导航到ViewModel A的视图后,Unity会成功注入父类(其中有一个实例).我还使用Unity存储AutoMapper实例.然后,我需要在viewmodel中用于以后映射对象.

I have been using a unity container and WPF and Prism. When the view of ViewModel A is navigated to, then Unity successfully injects the parent class (of which there is one instance). I also use Unity to store the AutoMapper instance. Which I then need in the viewmodel to map objects later.

推荐答案

我必须稍微更改视图模型并将父级从构造函数中删除.

I had to change my viewmodel slightly and removed the parent from the constructor.

我通过在自己的个人资料中加入Constructusing解决了映射器问题,例如:

I resolved the mapper issue by including the Constructusing in my profile like such:

public Profile()
{
            CreateMap<ModelB, ViewModelB>()
                .PreserveReferences().ConstructUsing((a, context) => new ViewModelB(context.Mapper))
                .ForMember(c => c.Parent, opt => opt.MapFrom(s => s.Parent))
                c.Players));
}

这篇关于使用自动映射器在构造函数中映射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆