将属性映射到集合项

将属性映射到集合项

本文介绍了将属性映射到集合项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在仔细阅读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 }));

这篇关于将属性映射到集合项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 10:28