使用自动映射器在构造函数中映射对象

编程入门 行业动态 更新时间:2024-10-22 13:46:23
本文介绍了使用自动映射器在构造函数中映射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

使用自动映射器在构造函数中映射对象

本文发布于:2023-11-16 11:47:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1604003.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   对象   映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!