根据文档,应尽可能为 AutoMapper 自动设置 PreserveReferences。
从 6.1.0 开始,PreserveReferences 会尽可能在配置时自动设置。
https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide
我也尝试将 MaxDepth 设置为 1,但我仍然得到以下映射的堆栈溢出异常。我可以以某种方式解决这个问题还是需要修改视图模型?
cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
.MaxDepth(1)
.EqualityComparison((src, dst) => src.Id == dst.Id);
导致堆栈溢出异常的代码:
var article = await iArticleRepository.GetAsync(id);
//The mapping below causes the exception
var mappedArticle = Mapper.Map<ArticleViewModel>(article);
实体:
public class Article: IEntity<int>
{
[Key]
public int Id { get; set; }
...
public int SupplierId { get; set; }
public virtual Supplier Supplier { get; set; }
}
public class Supplier: IEntity<int>
{
[Key]
public int Id { get; set; }
...
public virtual ICollection<Contact> Contacts { get; set; }
}
public class Contact: IEntity<int>
{
[Key]
public int Id { get; set; }
...
public virtual ICollection<Supplier> Suppliers { get; set; }
}
查看型号:
public class ArticleViewModel
{
public int Id { get; set; }
...
public SupplierViewModel Supplier { get; set; }
}
public class SupplierViewModel
{
public int Id { get; set; }
...
public List<ContactViewModel> Contacts { get; set; }
}
public class ContactViewModel
{
public int Id { get; set; }
...
public List<SupplierViewModel> Suppliers { get; set; }
}