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)
秒超载?
'configuration.CreateMap()'和你的代码有什么区别?我认为这是我尝试的默认行为 –
mihkov
,但它不起作用。我也遇到同样的麻烦。任何人都有解决方法吗? – Sauron
@Sauron我刚刚测试过,以确保'CreateMap()'是您正确配置对象并按照预期递归子集合所需的配置。我上面发布的配置是默认行为,正如已经指出的那样。 –