1

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

// 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)??

4

1 回答 1

1

在指定子成员映射的地方试试这个;

configuration.CreateMap<Tomato, TomatoViewModel>()
.ForMember(t => t.Children, options => options.MapFrom(source => source.Children));
于 2016-06-13T13:18:42.680 回答