我有两个数据模型,一个用于数据库,一个用于视图模型,例如
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)); }更多推荐
使用自动映射器在构造函数中映射对象
发布评论