I am using Automapper in order to be able to map my Entities to DTOs. Some of my entities are in many-to-many relationship and when I perform the mapping I get stack overflow error:
This is my entity and corresponding entity dto:
public partial class Group
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Group()
{
Tags = new HashSet<Tag>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
[StringLength(2147483647)]
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Tag> Tags { get; set; }
}
public partial class Tag
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Tag()
{
Groups = new HashSet<Group>();
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
[Required]
[StringLength(2147483647)]
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Group> Groups { get; set; }
}
As you can see, this is many to many relationship between Groups and Tags.
My DTOs look like this:
public class GroupDto
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<TagDto> Tags { get; set; }
public ICollection<long> TagIds { get; set; }
}
public class TagDto
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<GroupDto> Groups { get; set; }
}
Mapping configuration looks like this:
CreateMap<Group, GroupDto>();
CreateMap<GroupDto, Group>();
CreateMap<Tag, TagDto>();
CreateMap<TagDto, Tag>();
The exception gets fired from here:
var groupEntity = this._unitOfWork.GroupRepository.GetGroups().FirstOrDefault(g => g.Id == id);
if (groupEntity == null)
return null;
var groupAsDto = this._mapper.Map<Group, GroupDto>(groupEntity);
How can I avoid this and get a proper DTO from the Entity? I observed the Entity returned by the repository and it is as expected.