如何将AutoMapper与eager-loading和集合一起使用?

时间:2012-08-25 13:17:47

标签: asp.net-mvc

此语句返回人员及其地址和电话号码的列表。

var listOfPeople = db.People.AsQueryable();

现在,我想使用AutoMapper将上述LINQ语句的结果映射到视图模型。创建视图模型主要是为了防止某些属性返回给客户端/用户。

如何让AutoMapper将结果listOfPeople映射到由Person和{{ICollections的基础对象AddressesPhoneNunmbers组成的视图模型1}?我将单个人映射到单个虚拟机时没有问题。我想我已经挂断了一个集合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; }

}

1 个答案:

答案 0 :(得分: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

相关问题