How do I use AutoMapper with eager-loading and collections?
此语句返回人员及其地址和电话号码的列表。
1 | var listOfPeople = db.People.AsQueryable(); |
现在,我想使用 AutoMapper 将上述 LINQ 语句的结果映射到视图模型。创建视图模型主要是为了防止某些属性返回给客户端/用户。
如何让 AutoMapper 将结果
我使用的是
这是视图模型
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } |
如果我理解你的问题,不需要单独配置集合映射,你只需要定义类之间的映射(正如你已经完成的那样),集合将被自动处理
AutoMapper only requires configuration of element types, not of any
array or list type that might be used. For example, we might have a
simple source and destination type:
1 2 3 4 5 6 7 8 9 | public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } |
All the basic generic collection types are supported:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); |
列表和数组