具有相同类型的自动映射子列表

时间:2016-06-13 08:35:37

标签: asp.net .net asp.net-mvc-5 ef-code-first automapper-4

我有可能有孩子的实体,他们的孩子可能有孩子等等...... 当我获得数据库模型时,所有实体都可以使用正确的子项和父项。但是当我想映射到视图模型时问题出现了: 有没有办法从这样的数据库中映射模型?

// 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。试过

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

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

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

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

的第二次重载

1 个答案:

答案 0 :(得分:1)

在指定子成员映射的位置尝试此操作;

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