2012-01-20 18 views
1

假設如下:使用AutoMapper如何在不使用AfterMap的情況下從映射父對象到子集合成員獲取值?

public class ParentSource 
{ 
    public Guid parentId { get; set; } 

    public ICollection<ChildSource> children { get; set; } 
} 

public class ChildSource 
{ 
    public Guid childId { get; set; } 
} 

public class ParentDestination 
{ 
    public Guid parentId { get; set; } 

    public ICollection<ChildDestination> children { get; set; } 
} 

public class ChildDestination 
{ 
    public Guid childId { get; set; } 
    public Guid parentId { get; set; } 
    public ParentDestination parent; 
} 

一個人如何填充使用AutoMapper不使用.AfterMap家長的信息ChildDestination對象?

+0

使用AfterMap有什麼問題? – PatrickSteele

+0

很可能什麼也沒有。我認爲我遇到的實體框架錯誤促成了這個問題,畢竟是無關緊要的。但是,如果完全可能,我仍然很好奇。實際上它可能是通過.ForMember()中的地圖配置選項。 –

+0

沒有通過IMemberConfigurationOptions –

回答

1

我想填充集合中的一個子對象通過的父實例的引用的唯一途徑不使用.AfterMap()的會員集合是自定義TypeConverter<TSource, TDestination>。可以使用.AfterMap()。 :)

1

正如您在評論中所述,如果您不想使用AfterMap,ForMember將是另一種選擇。您可以創建一個ForMember轉換器,使用linq,可以非常快速地循環遍歷源子項,將它們轉換爲目標子項,然後設置Parent屬性。

或者你可以使用AfterMap。 :)

UPDATE:

也許是這樣的(未經測試):

.ForMember(d => d.children, 
    o => o.MapFrom(s => 
     from child in s.children 
     select new ChildDestination { 
      childId = child.childId, 
      parentId = s.parentId, 
      parent = s 
     })); 
+0

確定,但如果有人採用.ForMember()方法,您如何訪問該集合的源成員的父級? –

+0

我用一種可能的方式更新了我的答案。 – PatrickSteele

+0

幾乎,父對象的設置不正確。 ChildDestination上的父級是ParentDestination對象的一個​​實例。如果你實現了一個Mapper.Map語句來「強制」實例,我想你實際上開始了一個奇怪的遞歸,它實際上並沒有引用ParentDestination實例,它仍然只創建新映射的實例。 –

相關問題