AutoMapper - 映射视图模型子集合 [英] AutoMapper - mapping child collections in viewmodel
问题描述
我有一个需要显示某个的IEnumerable
字段分号分隔文本框一个ViewModel。起初我以为使用 DefaultModelBinder
来改造它,但我遇到了麻烦思考如何实现它在两个方向(DTO< - >视图模型)。
I have a viewmodel that needs to display a certain IEnumerable
field as semicolon-separated textbox. At first I thought of using DefaultModelBinder
to transform it, but I had trouble thinking how to achieve it in both directions (dto <-> viewmodel).
绰号是我想显示为一个TextBox,用分号分开场。
Nicknames is the field I'm trying to display as one textbox separated by semicolon.
public class Parent
{
public IEnumerable<Child> Children { get; set; }
}
public class Child
{
public IEnumerable<string> Nicknames { get; set; }
}
所以我决定尝试AutoMapper,我创建了两个的ViewModels:
So I decided to try AutoMapper, I created two ViewModels:
public class ParentViewModel
{
public IEnumerable<ChildViewModel> Children { get; set; }
}
public class ChildViewModel
{
public string Nicknames { get; set; }
}
然后,我创建的映射,喜欢本作的儿童(不再赘述其他路转换)
Then, I created mappings, like this for the children (omitted the other-way conversion for brevity)
Mapper.CreateMap<Child, ChildViewModel>().ForMember(
d => d.Nicknames, o => o.ResolveUsing<ListToStringConverter>().FromMember(s => s.Nicknames);
然后,父,创造了一个天真的地图(再次,省略了其他路)
Then, for the parent, created a naive map (again, omitted the other-way)
Mapper.CreateMap<Parent, ParentViewModel>();
我真的希望孩子映射自动发生,但他们没有,我已经创造了太多的正确的code,解决一个非常简单的问题,这在其他任何简单的/老的非MVC环境,我会用很长的时间前完成:)我怎么能继续,并告诉AutoMapper无需编写的另一个孩子们成员解析改造的孩子们。
I truly expected the child mappings occur automatically, but they don't, I've already created too much "proper" code to solve a really simple problem which in any other simpler/older non-MVC environment, I'd be done with a long time ago :) How can I proceed and tell AutoMapper to transform the children without writing another "children member resolver".
我有这个overthought并有一个简单的方法?
Have I overthought this and there's a simpler way?
感谢您!
推荐答案
尝试
Mapper.CreateMap<Parent, ParentViewModel>();
Mapper.CreateMap<Child, ChildViewModel>();
var v = Mapper.Map<Parent, ParentViewModel>(parent);
这篇关于AutoMapper - 映射视图模型子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!