2012-08-25 25 views
0

該聲明返回人員及其地址和電話號碼列表。如何在急速加載和集合中使用AutoMapper?

var listOfPeople = db.People.AsQueryable(); 

現在,我想使用AutoMapper將上述LINQ語句的結果映射到視圖模型。視圖模型主要是爲了防止某些屬性返回給客戶端/用戶而創建的。

如何獲得AutoMapper的結果,listOfPeople映射,基礎對象,Person組成的視圖模型,並AddressesPhoneNunmbersICollections?我沒有將單個人映射到單個虛擬機的問題。我想我會掛上映射一個集合listOfPeople,其中包含一些集合。

我使用ASP.NET Web API 4,不MVC 4

這裏是視圖模型

public class BasicApiViewModel 
{ 
    public int Id { get; set; } 

    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    public virtual ICollection<Address> Addresses { get; set; } 

    public virtual ICollection<Phone> Phones { get; set; } 

} 

回答

0

如果我明白你的問題,沒有必要單獨配置的集合映射,你只需要定義類之間的映射(如你已經完成的),集合將自動處理

AutoMapper只需要配置元素類型,而不是任何可能使用的數組或列表類型。例如,我們可能有一個 簡單的源和目標類型:

public class Source 
{ 
    public int Value { get; set; } 
} 

public class Destination 
{ 
    public int Value { get; set; } 
} 

所有基本泛型集合類型的支持:

Mapper.CreateMap<Source, Destination>(); 

var sources = new[] 
    { 
     new Source { Value = 5 }, 
     new Source { Value = 6 }, 
     new Source { Value = 7 } 
    }; 

IEnumerable<Destination> ienumerableDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources); 
ICollection<Destination> icollectionDest = Mapper.Map<Source[], ICollection<Destination>>(sources); 
IList<Destination> ilistDest = Mapper.Map<Source[], IList<Destination>>(sources);  
List<Destination> listDest = Mapper.Map<Source[], List<Destination>>(sources); 
Destination[] arrayDest = Mapper.Map<Source[], Destination[]>(sources); 

Lists and arrays

+0

我還需要爲電話號碼和地址的集合映射類。然後,一切按預期工作。謝謝! – Scott

相關問題