2012-05-30 132 views
0

我能夠使用下面的代碼將同一集合的集合映射到單個集合。使用Automapper將多個集合映射到單個集合

AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
       dest => dest.Drivers, 
       opt => opt.MapFrom(src => src.BikeDrivers.Concat(src.CarDrivers).Concat(src.TruckDrivers))); 

通過上述解決方案,我可以將所有三種類型的驅動程序映射到一個集合中。 我的目標對象(Driver)有一個名爲DriverType的屬性,它有助於識別驅動程序的類型。 (BikeDriver/CarDriver/TruckDriver)

在上面的代碼中,我如何根據我添加的集合設置DriverType屬性。

爲如:我有硬編碼

DriverType = CarDriver爲CarDrivers藏品 DriverType = BikeDriverfor BikeDrivers集合項目。

在此先感謝

回答

1

設置,你必須在你的源對象這方面的知識DriverType財產。我看不到你的大圖,但這可能用作樣本

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var s = new Source() 
         { 
          BikeDrivers = new List<BikeDriver>() {new BikeDriver()}, 
          CarDrivers = new List<CarDriver>() {new CarDriver()}, 
          TruckDrivers = new List<TruckDriver>() {new TruckDriver()}, 
         }; 

      var d = new Destination(); 


      AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
       dest => dest.Drivers, 
       opt => opt.MapFrom(src => src.BikeDrivers.Concat<IDriver>(src.CarDrivers).Concat<IDriver>(src.TruckDrivers))); 

      var result = AutoMapper.Mapper.Map(s, d); 
     } 

     public class Driver : IDriver 
     { 
      public string DriverType { get; set; } 
     } 

     public class Destination 
     { 
      public IEnumerable<IDriver> Drivers { get; set; } 
     } 

     public class Source 
     { 
      public IEnumerable<BikeDriver> BikeDrivers { get; set; } 
      public IEnumerable<CarDriver> CarDrivers { get; set; } 
      public IEnumerable<TruckDriver> TruckDrivers { get; set; } 
     } 

     public interface IDriver 
     { 
      string DriverType { get; set; } 
     } 

     public class BikeDriver : IDriver 
     { 
      public string DriverType 
      { 
       get { return "BikeDriver"; } 
       set { throw new NotImplementedException(); } 
      } 
     } 
     public class CarDriver : IDriver 
     { 
      public string DriverType 
      { 
       get { return "CarDriver"; } 
       set { throw new NotImplementedException(); } 
      } 
     } 
     public class TruckDriver : IDriver 
     { 
      public string DriverType 
      { 
       get { return "TruckDriver"; } 
       set { throw new NotImplementedException(); } 
      } 
     } 
    } 
}