According to the documentation PreserveReferences should be set automatically whenever possible for AutoMapper.
Starting from 6.1.0 PreserveReferences is set automatically at config time whenever possible.
https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide
I have also tried setting MaxDepth to 1 but I still get a stack overflow exception with the following mapping. Can I get around this somehow or do I need to modify the view models?
cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
.MaxDepth(1)
.EqualityComparison((src, dst) => src.Id == dst.Id);
Code that causes the stack overflow exception:
var article = await iArticleRepository.GetAsync(id);
//The mapping below causes the exception
var mappedArticle = Mapper.Map<ArticleViewModel>(article);
Entities:
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; }
}
View models:
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; }
}