2010-09-21 21 views
2

比方說,我有以下實體:如何配置AutoMapper將所有引用類型的集合轉換爲整數集合?

public class Store 
{ 
    public List<Product> Products { get; set; } 
    public List<Employee> Employees { get; set; } 
    public List<Camera> Cameras { get; set; } 
} 

換句話說,有一個ProductsStoreEmployees和安全Cameras。我想轉換此StoreStoreDTO

public class StoreDTO 
{ 
    public List<int> ProductIds { get; set; } 
    public List<int> EmployeeIds { get; set; } 
    public List<int> CameraIds { get; set; } 
} 

換句話說,該StoreDTO只需將實體ID。

現在,我使用這個代碼來設置AutoMapper

Mapper.CreateMap<Product, int>().ConvertUsing(x => x.Id); 
Mapper.CreateMap<Employee, int>().ConvertUsing(x => x.Id); 
Mapper.CreateMap<Camera, int>().ConvertUsing(x => x.Id); 

正如你所看到的,這是一個很大的樣板代碼。有什麼辦法來配置AutoMapper自動轉換引用類型的所有集合到整數集合?

+0

你也可以使用valueinjecter並創建只有一個注射是從ID會映射到一個int和使用任何類型的,你需要 – Omu 2010-09-24 19:17:51

回答

1

我們這樣做是有超過反思了一下LINQ的。您可以使用LINQ來查詢從Product,Employee和Camera的某些基類派生的所有類型。接下來,循環調用CreateMap和ConvertUsing方法。

有沒有種掃描可言這是爲什麼這樣的事情是不是真的存在。但根據需要進行自己的類型掃描也不錯。

+0

感謝。最後,我意識到編寫反射代碼需要更多的工作,而不是僅僅明確映射幾個類。 – 2010-09-22 20:10:08

相關問題