如何映射与Automapper和EntityFramework的多对多关系

时间:2016-10-11 08:40:19

标签: entity-framework many-to-many automapper

我正在使用Automapper,以便能够将我的实体映射到DTO。我的一些实体处于多对多关系中,当我执行映射时,我得到堆栈溢出错误:

enter image description here

这是我的实体和相应的实体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; }
    }

正如您所看到的,群组标记之间存在多对多关系。

我的DTO看起来像这样:

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; }
    }

映射配置如下所示:

CreateMap<Group, GroupDto>();
CreateMap<GroupDto, Group>();

CreateMap<Tag, TagDto>();
CreateMap<TagDto, Tag>();

从这里触发了异常:

var groupEntity = this._unitOfWork.GroupRepository.GetGroups().FirstOrDefault(g => g.Id == id);

            if (groupEntity == null)
                return null;

             var groupAsDto = this._mapper.Map<Group, GroupDto>(groupEntity);

如何避免这种情况并从实体获得适当的DTO?我观察了存储库返回的实体,它是预期的。

0 个答案:

没有答案