0

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

var listOfPeople = db.People.AsQueryable();

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

如何让 AutoMapper 将结果 、 映射到由基础对象 、和 和组成的listOfPeople视图模型?我将一个人映射到一个虚拟机没有问题。我想我正忙于映射一个集合,其中包含几个集合。PersonICollectionsAddressesPhoneNunmberslistOfPeople

我正在使用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; }

}
4

1 回答 1

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);

列表和数组

于 2012-08-25T13:39:21.607 回答