2010-02-16 91 views
2

我有從LINQ to SQL實體派生的父對象和子對象。我想將這些映射到一些更友好的DTO上。我的SQL實體類看起來有點像這樣:如何在AutoMapper中映射此父子關係?

public class SqlEntityParent 
{ 
    public int ParentId { get; set; } 
    public string Name { get; set; } 
    public EntitySet<SqlEntityChild> Children { get; set; } 
} 

public class SqlEntityChild 
{ 
    public int ChildId { get; set; } 
    public int ParentId { get; set; } 
    public int Position { get; set; } 
    public string CategoryName { get; set; } 
    public string CategoryValue { get; set; } 
} 

在這種模式下,它的SqlEntityParentSqlEntityChild之間的標準一個一對多的關係。一些有代表性的數據會...

家長:

 
ParentId Name 
-------- ------- 
1   Parent1 

兒童:

 
ChildId ParentId Position CategoryName CategoryValue 
------- -------- -------- ------------ ------------- 
1  1   1   Contents  Things 
2  1   1   Group   GroupOne 
3  1   2   Contents  Things 
4  1   2   Group   GroupTwo 

現在我想這些數據映射到我的域對象,這看起來有點像這個:

public class DomainParent 
{ 
    public int ParentId { get; set; } 
    public string Name { get; set; } 
    public List<DomainChild> Children { get; set; } 
} 

public class DomainChild 
{ 
    public int Position { get; set; } 
    public string Contents { get; set; } 
    public string Group { get; set; } 
} 

在此結構中,單個對象由來自兩個SqlEntityChild對象的數據組成,並且該組由子實體的值Position確定。因此,這些示例數據代表一個具有兩個DomainChild對象列表的單個DomainParent對象。第一個孩子應具有1的Position,「東西」的Contents值和「GroupOne」的值Group。第二個孩子應該有一個Position的2,一個Contents的「事情」,和一個Group「GroupTwo」。

我很喜歡使用ValueResolvers在AutoMapper中設置一對一的自定義映射,但我不確定如何最好地處理這個問題。我爲父實體創建了下面的解析器和相關映射,它們將整個子實體列表映射到一個遍中,但看起來很愚蠢,因爲我必須在此解析器類中手動完成子對象的整個映射。

Mapper.CreateMap<SqlEntityParent, DomainParent>() 
    .ForMember(dto => dto.Children, opt => opt.ResolveUsing<MyResolver>()); 


public class MyResolver: ValueResolver<SqlEntityParent, List<DomainChild>> 
{ 
    private MyDataContext db; 

    public MyResolver() 
    { 
     db = new MyDataContext(); 
    } 

    protected override List<DomainChild> ResolveCore(SqlEntityParent source) 
    { 
     // In here: 
     // 1. custom LINQ queries 
     // 2. manual creation of DomainChild objects 
     // 3. manual mapping of SqlEntityChild to DomainChild 
    } 
} 

所以,我的主要問題是:這是在這種情況下,我可以AutoMapper做的最好的,或者是有,我可以使用一些其他更有效的方法是什麼?

回答

0

通常在這些情況下,我們直接從SqlEntityChild映射到DomainChild,因爲列表,數組等自動受支持。您只需要爲元素類型設置映射,因爲除了遍歷原始的Children集合之外,沒有額外的邏輯。

+0

感謝您的回覆。我仍然不確定如何設置從多個SqlEntityChild對象到一個DomainChild的映射。我當然希望能夠做你的建議,但看起來像我見過的所有例子都有這種映射的隱含的一對一要求。我是否需要更改SqlEntityChild的定義,以便* it *在配置映射到DomainChild之前更好地聚合多條記錄? – 2010-02-18 19:01:56