![](/img/trans.png)
[英]How to use AutoMapper to map destination object with a child object in the source object?
[英]Automapper - How to map from source child object to destination
我試圖從源的子對象映射到目標(作為父對象)。
來源模型:
public class SourceBaseResponse<T> where T : new()
{
public string Type { get; set; }
public string Id { get; set; }
public T Attributes { get; set; }
}
對於我的例子,我使用的是SourceAssignment類型
public class SourceAssignment
{
public string Id { get; set; }
public string Email { get; set; }
public string EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTimeOffset CreatedAt { get; set; }
}
目標對象
public class DestinationAssignment
{
public string Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我想將Source Model直接映射到Destination。 所以,我試圖使用
CreateMap<SourceAssignment, DestinationAssignment>();
CreateMap<SourceBaseResponse<SourceAssignment>, DestinationAssignment>()
.ForMember(dest => dest, opt => opt.MapFrom(src => AutoMapperConfig.Mapper.Map<DestinationAssignment>(src.Attributes)));
這不起作用,因為我在上面的行中出現“運行時錯誤”,“僅對類型的頂級個人成員支持成員的自定義配置”。
所以,根據這個帖子,我嘗試了以下內容
CreateMap<SourceBaseResponse<SourceAssignment>, DestinationAssignment>()
.AfterMap((src, dst) => Mapper.Map(src.Attributes, dst));
現在,我收到錯誤,其中應該發生映射,其中顯示“Mapper未初始化。使用適當的配置調用Initialize。如果您嘗試通過容器或其他方式使用映射器實例,請確保您沒有對靜態Mapper的任何調用。映射方法,如果您正在使用ProjectTo或UseAsDataSource擴展方法,請確保傳入適當的IConfigurationProvider實例。“
我可以為每個屬性使用ForMember,並將它從src.Attributes映射到dest(例如:src.Attribute.Id到dest.Id)。 這是有效的,但我真的不想這樣做,因為我的Source是涉及嵌套子節點的復雜類(因為這是一個Web API響應,我無法控制它)。 所以這里完成了很多自定義映射
CreateMap<SourceAssignment, DestinationAssignment>();
有關如何進行的任何建議。
需要解析上下文才能調用Mapper.Map(),您可以使用ConstructUsing()獲取解析上下文:
CreateMap<SourceChild, Destination>();
CreateMap<Source, Destination>()
.ConstructUsing((src, ctx) => ctx.Mapper.Map<Destination>(src.SourceChild));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.