将属性映射到集合项

编程入门 行业动态 更新时间:2024-10-27 19:16:24
本文介绍了将属性映射到集合项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在仔细阅读AutoMapper文档,以尝试找到针对此问题的推荐解决方案,但未能找到它.

I've been sifting through AutoMapper documentation to try and find a recommended solution to this but haven't been able to find it.

假设我有一个类似以下的课程

Let's say I have a class like the following

public class Foo { public string Note { get; set; } }

该类从客户端填充,并映射到以下域对象类

this class gets populated from the client and gets mapped to the following domain object class

public class Bar { public IList<Note> Notes { get; set; } }

注释在哪里

public class Note { public string Text { get; set; } // other properties excluded for brevity }

我想将Foo上的Note字符串属性映射到Note的新实例上的Text属性,然后将该Note添加到Notes上的Notes集合中c6>.我正在使用ValueResolver执行该操作的第一部分(将字符串映射到Note的新实例),但是不确定如何进行第二部分(将该项目映射到集合).

I'd like to map the Note string property on Foo, firstly to the Text property on a new instance of Note and then add that Note to the Notes collection on Bar. I'm using a ValueResolver to perform the first part of this operation (mapping the string to a new instance of Note) but am not sure about how to go about the second part (mapping that item to a item in a collection).

最干净的方法是什么?

推荐答案

我在想这样的事情应该起作用(未经测试-只是大声键入):

I'm thinking something like this should work (not tested -- just typing out loud):

Mapper.CreateMap<Foo, Bar>().ForMember(d => d.Notes, opt => opt.MapFrom(s => new List<Note> { new Note { Text = s.Note } });

编辑

您还可以使用AutoMappers AfterMap功能.这个lambda将在Automapper完成常规映射后执行:

You could also use AutoMappers AfterMap functionality. This lambda would be executed after Automapper has done it's regular mappings:

.AfterMap((s,d) => d.Notes.Add(new Note { Text = s.Note }));

更多推荐

将属性映射到集合项

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

发布评论

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

>www.elefans.com

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