我有一个我从客户端收到的视图模型,看起来像这样
public class Orderviewmodel { public string Name{get;set;} public string ContactDetails {get;set;} public List<FunkyThing_viewmodel> {get;set;} } public class FunkyThing_viewmodel { public string ThingName{get;set;} public string Colour{get;set;} public string Size{get;set;} }
我希望将其映射到域模型列表,其中每个模型看起来更像这样:
public class Order { public string Name{get;set;} public string ContactDetails {get;set;} public string ThingName{get;set;} public string Colour{get;set;} public string Size{get;set;} }
所以我想要最终看到这样的东西:
List<Order> orders = new Orders(); Mapper.CreateMap<Orderviewmodel,List<Order>>(); //Something in here to ensure each funky thing creates an additional order.... Mapper.Map(viewmodel,orders);
解决方法
using System.Collections.Generic; using System.Linq; using AutoMapper; using NUnit.Framework; using SharpTestsEx; namespace StackOverflowExample.Automapper { public class Orderviewmodel { public string Name { get; set; } public string ContactDetails { get; set; } public List<FunkyThingviewmodel> FunkyThingviewmodels { get; set; } } public class FunkyThingviewmodel { public string ThingName { get; set; } public string Colour { get; set; } public string Size { get; set; } } public class Order { public string Name { get; set; } public string ContactDetails { get; set; } public string ThingName { get; set; } public string Colour { get; set; } public string Size { get; set; } } [TestFixture] public class FlattenWithListTests { [Test] public void FlattenListTest() { //arrange var source = new Orderviewmodel { Name = "name",ContactDetails = "contact",FunkyThingviewmodels = new List<FunkyThingviewmodel> { new FunkyThingviewmodel {Colour = "red"},new FunkyThingviewmodel {Colour = "blue"} } }; Mapper.CreateMap<FunkyThingviewmodel,Order>(); Mapper.CreateMap<Orderviewmodel,List<Order>>() .ConvertUsing(om => om.FunkyThingviewmodels.Select( ftvm => { var order = Mapper.Map<Order>(om); Mapper.Map(ftvm,order); return order; }).ToList()); //act var mapped = Mapper.Map<List<Order>>(source); //assert mapped[0].Satisfy(m => m.Name == source.Name && m.ContactDetails == source.ContactDetails && m.Colour == "red"); mapped[1].Satisfy(m => m.Name == source.Name && m.ContactDetails == source.ContactDetails && m.Colour == "blue"); } } }