【问题标题】:Map LLBLGen entity to DTO将 LLBLGen 实体映射到 DTO
【发布时间】:2015-12-28 13:58:05
【问题描述】:

我正在尝试使用 AutoMapper 在 LLBLGen 实体和 DTO 之间创建映射。

我的 DTO 如下所示:

// Parent
public int Id { get; set; }
public List<Child> Children{ get; set; } // One to Many

// Child
public int Id { get; set; }
public int Parent { get; set; } // Foreign key to parent Id

ParentEntity 包含一个与 DTO 列表同名的 ChildCollection 和一个 Id(以及需要忽略的其他 LLBL 字段)。因此,当 ParentEntity 映射到 Parent DTO 时,它还应该将 ChildCollection 映射到子列表。

这是我目前得到的:

ParentEntity parentEntity = new ParentEntity(id);

AutoMapper.Mapper.CreateMap<ParentEntity, Parent>();
AutoMapper.Mapper.CreateMap<ChildCollection, List<Child>>();

var parent = AutoMapper.Mapper.Map<Parent>(parentEntity);

这会导致 Id 被映射,但 List 的计数为 0。

我怎样才能让它工作?


更新:

尝试与我之前的尝试相同,但手动映射子列表也会导致相同的问题:ID 被映射但列表为空。

Mapper.CreateMap<ParentEntity, Parent>()
    .ForMember(dto => dto.Children, opt => opt.MapFrom(m => m.Children));

【问题讨论】:

  • 请出示ChildCollection类。其List 属性的类型是什么?我认为最好提供实体和 DTO 的完整相关源代码来解决映射不起作用的原因。
  • 我的问题中已经显示了 DTO。 ChildCollection 包含 ChildEntities,其中包含与 DTO 相同的字段以及更多与 LLBL 相关的资源。粘贴这些集合/实体的全部资源不会有用而且太多。如果您之前使用过 LLBL,那么您应该对这些类包含的内容有所了解。

标签: c# asp.net automapper dto llblgenpro


【解决方案1】:

此行没有帮助:

AutoMapper.Mapper.CreateMap<ChildCollection, List<Child>>();

您应该添加显式映射类到类:

AutoMapper.Mapper.CreateMap<ChildEntity, Child>();

然后您应该指定要映射的确切属性。两个属性都应具有 List 类型或类似类型(List&lt;ChildEntity&gt; 作为源,List&lt;Child&gt; 作为目标)。因此,如果ParentEntityParent 类都具有Children 属性,您甚至不必指定:

.ForMember(dto => dto.Children, opt => opt.MapFrom(m => m.Children));

足够的默认映射:

  Mapper.CreateMap<ParentEntity, Parent>();

【讨论】:

  • 你找到了!解决方案是 ChildEntity 和 Child DTO 需要一个明确的类到类映射。我认为问题更复杂,并且与您提到的 List 类型不相似有关,因为 LLBL 具有自定义 List 实现(EntityCollections)。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-09-13
  • 2021-12-31
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
相关资源
最近更新 更多