Automapper将子列表映射到同一类型 [英] Automapper map child list with from same type

查看:443
本文介绍了Automapper将子列表映射到同一类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可能有孩子的孩子,孩子可能有孩子等等...
当我获得数据库模型时,所有实体都可以正确的孩子和父母。但是当我想要映射以查看模型时,问题出现在:
有没有可能的方式从这样的数据库映射模型?

I have entities that may have children and their children may have children and so on... When I get database models all entities are OK with correct children and parent. But the problem comes when I want to map to view model: Is there any possible way to map models from database like this?

// database model code first
public class Tomato
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int? ParentId { get; set; }

    public virtual Tomato Parent { get; set; }

    public ICollection<Tomato> Children { get; set; }
}

// mvc view model
public class TomatoViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int? ParentId { get; set; }

    public ICollection<TomatoViewModel> Children { get; set; }
}

配置 configuration.CreateMap< Tomato,TomatoModel> (),但尝试绑定子元素时会抛出 StackOverflowException 。试用

Configured configuration.CreateMap<Tomato, TomatoModel>() but throws an StackOverflowException when try to bind child elements. Tried with

configuration.CreateMap<Tomato, TomatoViewModel>().ForMember( t => t.Children,
                options => options.Condition(context => (context.SourceValue as Tomato).ParentId == this.Id));
// this.Id refers to TomatoViewModel.Id

更新:在我的控制器类中:

Update: in my controller class:

var models = foodIngredientsService.GetAllTomatoes().Where(t => t.ParentId == null).To<TomatoModel>().ToList();

第二个问题:如何使用 options.Condition(Func< TomatoModel,bool> func) ??

推荐答案

您指定子成员映射;

configuration.CreateMap<Tomato, TomatoViewModel>()
.ForMember(t => t.Children, options => options.MapFrom(source => source.Children));

这篇关于Automapper将子列表映射到同一类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆